Blog Home  Home Feed your aggregator (RSS 2.0)  
kevin Mocha - DotNet
Bookmarks collected from web.
 
 Sunday, March 14, 2010
 Friday, March 12, 2010


It is possible to set a minumum length e.g.
string.format("{0,10:s}",12345"); will return a string 10 chars long with right alignment

string.format("{0,10:s}",12345"); will return a string 10 chars long with left alignment

Friday, March 12, 2010 10:02:29 PM UTC  #    Comments [0]    |  Trackback
 Wednesday, March 10, 2010

Well-designed databases can pose a problem for developers.

In the data world, a database is designed for maintainability, security, efficiency, and scalability. Its data is organized in a way that satisfies the demands of a good database administrator, yet provides challenges for the developer who needs to access that data.

 

The EDM follows this concept, but in the Entity Framework, it moves the modeling into XML files that different programming models can use. The primary XML file contains the conceptual model, which is the actual EDM. A second XML file contains a representation of the database and a third, the mapping between the first two. At design time, all three files are bundled into a single EDMX file. The build process splits the EDMX out into the three metadata files that are used at runtime. The Entity Framework then provides a framework that allows developers to write .NET applications based on this model.

 

As long as the EDM provides the conceptual schema, a representation of the database, a mapping file, and access to an Entity Framework-aware ADO.NET provider for the target database, the Entity Framework doesn't care what database is being targeted. It provides a common means of interacting with the database, common query syntax, and a common method for sending changes back to the database.

Although the Entity Framework provides a very rich set of features for developers, its most important capabilities are the following:

  • It automatically generates classes from the model and updates those classes dynamically anytime the model changes.

  • It takes care of all of the database connectivity so that developers are not burdened by having to write lots of code for interacting with the database.

  • It provides common query syntax for querying the model, not the database, and then translates these queries into queries that the database can understand.

  • It provides a mechanism for tracking changes to the model's objects as they are being used in applications, and handles the updates to the database.

In addition, because the model's classes are dynamically generated, minor changes to the model need not have a major impact on your application. Furthermore, modifying the model is much simpler than modifying your objects and the data access code on which they rely.

 

Navigation properties are pointers to related entities.
An Entity Set is a container for a collection of entities of a single type.

Cleaning up the entity, property, and association names is a step that you should consider performing immediately after you create a new model with the ADO.NET Entity Data Model Wizard. In this way, as you begin to code against the model, the names of the objects will be logical. Additionally, if you change these names after you have begun to code, you will have to modify your code to reflect the changes.

 

The EDMX file is composed of two main sections: the runtime information and the Designer information. The runtime section comprises three additional sections: one each for storage models, conceptual models, and mappings. The Designer section specifies where the various model elements should be placed visually in the Designer.

 

image

 

Why use the storage layer to represent the data store when you have the actual data store to work with? There are a number of reasons to use this piece of the model. The most important reason is that this provides loose coupling to the database; not every object in the database needs to be in the mode

 

Although the entire model is contained in a single file at design time, when the project is compiled it will create three separate files—one for each of these sections. The conceptual layer is saved to a file with a .csdl extension, which stands for Conceptual Schema Definition Language. The storage layer is saved to a file with an .ssdl extension (which stands for Store Schema Definition Language) and the mapping layer is saved to a file with an .msl extension (which stands for Mapping Specification Language). These files are used at runtime, which is why they are contained in a section called edmx:Runtime in the model.

 

image

Although it makes sense to have a container for an entity because you could have many contact entities to work with, how would there be a collection of associations? When you are working with entity objects, the associations between the entities are also objects. If you have a single contact with multiple addresses in memory, there would be one FK_Address_Contact association object for each relationship. Figure 2-14 shows two association objects that are used to define relationships between a single contact and two addresses.

 

<NavigationProperty Name="Contact"

                      Relationship="ProgrammingEFDB1Model.FK_Address_Contact"

                       FromRole="Address" ToRole="Contact" />

 

The collection that is exposed in the Addresses navigation property is not a collection from the System.Collections namespace, but rather an EntityCollection. The EntityCollection is a completely unique class in the Entity Framework.

 

image

 

image

The ReferentialConstraint element serves a number of purposes. It specifies the direction of the relationship using the Principal and Dependent role elements. In the example, Address is dependent upon Contact. This also translates to defining the primary key/foreign key relationship, and we finally see the foreign key in the Address table identified: it is the ContactID. This is another piece of the puzzle of how the association and the navigation property work in the conceptual model. The ContactID property doesn't exist anywhere in the CSDL, but it is specified here in the SSDL. The MSL will show us how they are linked.

The last purpose of the ReferentialConstraint element is to stipulate that a row in the Address table cannot exist without a reference to a row in the People table.

If you check back at the CSDL's association in Example 2-2, you will see that this ReferentialConstraint doesn't exist. The CSDL enforces that constraint in a different way. The multiplicity for the Person entity type in that relationship is "1", not "0..1".

Designer's Mapping Details window

Open the model in the XML Editor again and expand the <edmx:Mappings> section; you'll see that there is one big difference in how the mapping is described under the covers. The mapping, as shown in Example 2-4, is being made from the EntitySet, not the actual entity. When you add inherited types into the mix, you may also be mapping Customers who are a type of Contact. When you map the EntitySet you cover all of the entity types in an inheritance hierarchy. Therefore, the mapping needs to be done to the EntitySet, not a specific entity.

 

image

image

The Entity Framework automatically creates a set of classes from the model. These classes are what you will work with when you query the model, and objects will be returned that are based on these classes.

Each time a change is made to the model and the model is then saved, the Entity Framework's code generator kicks in and the classes are re-created.

 

IQueryable is a LINQ query type. At design time, the compiler recognizes the LINQ query and does its best to tell you its return type. The compiler doesn't realize that because it is a LINQ to Entities query, it will be processed by the Entity Framework and will result in an ObjectQuery. ObjectQuery implements IQueryable, so the two are very closely related.

IQueryable contains metadata about the query, such as the query expression and the provider being used. ObjectQuery is an IQueryable with additional query details that are specific to Entity Framework queries.

The results are described as an "enumerable type," based on the class IEnumerable, which is similar to a Collection. An IEnumerable allows you to enumerate or iterate through each item in the collection as you did in the preceding code sample (i.e., in For Each/foreach). A Collection is an enhanced IEnumerable. Whereas an IEnumerable is read-only, the more familiar Collection class allows you to perform additional actions, such as adding or removing items from the group.

EntityClient: The Lowest-Level Method for Returning Streamed Data Through EDM Queries

//add new entities

image

//insert new parents and children

image

image

image

You can divide the core functionality of Object Services into seven areas:

  • Query processing

  • Object materialization

  • Object management

  • Object relationship management

  • Object state management

  • Database Manipulation Language (DML) command processing

  • Additional features

At a high level, query processing in the Entity Framework involves translating the LINQ or Entity SQL queries into queries that the data store can process. At a lower level, it first parses your query into a command tree of LINQ or Entity SQL query operators and functions, combined with the necessary entities and properties of your model. The command tree is a format that the various providers that have been designed to work with the Entity Framework will be expecting. Next, the provider API (Oracle, SQL Server, MySQL, etc.) transforms this tree into a new expression tree composed of the provider's operators and functions and the database's tables and columns. This tree is finally passed to the database.

LINQ starts its journey in the LINQ APIs and is then passed to the Object Services API. When you create a LINQ to Entities query, you are using syntax that is built into Visual Basic and C# that has enhancements that the Entity Framework has added. LINQ converts this query into a LINQ expression tree, which deconstructs the query into its common operators and functions. The LINQ expression tree is then passed to Object Services, which converts the expression tree to a command tree.

 

image

 

Customizing Entity Data Models

In object-oriented programming, when one object is a type of another object, you can use inheritance to share properties so that the properties of a base type (e.g., Contact) are exposed directly in a derived type (e.g., Customer). The EDM supports inheritance as well. The inheritance mapping used to allow Customer to derive from Contact and absorb Contact's properties is called Table per Type inheritance. Let's investigate this one first, and modify the model to simplify working with customers.

Entity splitting, also referred to as vertical splitting, allows you to map a single entity to more than one table. You can use entity splitting when tables share a common key; for example, if a contact's personal and business information is stored in separate tables. You can use entity splitting as long as the primary keys in the two database tables match.
(Entity splitting can solve this problem very easily, by mapping both the Customer table and the ContactPersonalInfo table to the Customer entity.)

Conditional mapping places a permanent filter on an entity by defining that an entity will be mapped to data in the database under only certain conditions.

Another type of inheritance that the EDM supports is Table per Hierarchy (TPH). TPH inheritance depends on conditional mapping. Rather than including only records that match the condition, the condition is used to define records as different types.

 

Creating Complex Types to Encapsulate Sets of Properties

 

QueryView is a mapping that allows you to override the default mapping for an entity set and return read-only data. QueryView is something you need to enter manually in the XML, and it belongs in the mapping layer.

A QueryView is a query that is expressed using Entity SQL syntax. However, rather than creating the Entity SQL expression against the conceptual layer of the model, the target of the expression is the store (SSDL) layer. In other words, when you construct the Entity SQL for a QueryView, the query is written against the elements of the SSDL.

Although QueryView returns read-only entities, if you want to use QueryView for some of its other benefits, you can force the entity to be updatable. Entities that are mapped with QueryView are still change-tracked by the ObjectContext. However, the Entity Framework is not able to automatically generate Insert, Update, and Delete commands for these entities. Instead, you can always create function mappings, as you did for the Payment entity. Then the entity that came from a QueryView will be affected by the call to SaveChanges.

In addition to returning read-only entities, another benefit of QueryView is that you can overcome the limitations of conditional mapping. As you saw earlier, conditional mapping lets you filter using =, Is Null, and Is Not Null.
Using a QueryView you can filter with a much wider variety of operators, including > and <. However, because QueryView returns read-only data, if you need the entity that results to be updatable, you can still achieve this by mapping stored procedures to the entity that results.

Wednesday, March 10, 2010 8:25:05 PM UTC  #    Comments [0]    |  Trackback
 Tuesday, March 09, 2010

http://www.codeproject.com/KB/webservices/Programming_WCF.aspx

The WCF programming model unifies Web Services, .NET Remoting, Distributed Transactions, and Message Queues into a single Service-oriented programming model for distributed computing. WCF uses SOAP messages for communication between two processes, thereby making WCF-based applications interoperable with any other process that communicates via SOAP messages.

A WCF Service is composed of three components parts viz,

1) Service Class - A WCF service class implements some service as a set of methods.

2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.

3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:

Address: The endpoints specify a Address that defines where the endpoint is hosted.

Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.

Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted.Various components of the WCF are depicted in the figure below.

Screenshot - WCF_Arch.gif

Who How What

There are three types of contracts namely,

Service Contracts - Describes the operations a service can perform. Maps CLR types to WSDL.
Data Contracts - Describes a data structure. Maps CLR types to XSD.
Messaga Contracts - Defines the structure of the message on the wire. Maps CLR types to SOAP messages.

Bindings can be defined in config file as well as programattically.

Services have behaviors that control their concurrency, throttling, transactions,
security, and other system semantics.

 

Metadata in WCF refers to the information that describes precisely how to
communicate with a service. Clients can request metadata from a running
service to learn about their endpoints and the message formats that they

require. At design time, clients send a request message defined by the
WS-MetadataExchange standard and receive WSDL in return. The WSDL
can be used by the client to define a proxy class and configuration file that
will later be used at runtime to communicate with the service. Figure 1.4
shows this interaction.

image

Use svcutil.exe to generate the proxy code

Tuesday, March 09, 2010 8:17:35 PM UTC  #    Comments [0]    |   |  Trackback
 Friday, March 05, 2010

Form 2.0 data binding

Binding nameBinding = new Binding("Text", this.raceCarDriver, "Name", true); 
this.nameTextBox.DataBindings.Add(nameBinding);
or 
this.nameTextBox.DataBindings.Add( "Text", this.raceCarDriver, "Name");

The minimum implementation that is considered a list data source by the Windows Forms binding engine is a class that implements the IList interface (from System.Collections).

this.BindingManager.Position = 0; 
RefreshItems();

this.raceCarDriversListBox.DataSource = this.raceCarDrivers;
this.raceCarDriversListBox.DisplayMember = "Name";

void addButton_Click(object sender, EventArgs e) {
  // Add item to list data source directly
  RaceCarDriver raceCarDriver = new RaceCarDriver("Nelson Piquet", 300);
  this.raceCarDrivers.Add(raceCarDriver);

  // Select new item
  this.BindingManager.Position = this.BindingManager.Count - 1;
}

private void deleteButton_Click(object sender, EventArgs e) {
  // Remove item from list data source directly
  this.raceCarDrivers.Remove(
    (RaceCarDriver)this.BindingManager.Current);
}

BindingList<T>->IBindingList->IList
BindingList<T> nicely implements the list management (AllowEdit, AllowNew, AllowRemove, and AddNew) and change notification (SupportsChangeNotification, ListChanged) functional subsets of IBindingList.[5] And because it's generic, it can turn any type into a strongly typed list data source with data-binding-savvy list management and change notification using something like the following code

Two-Way Item Change Synchronization

When the values in a DataGridView row are changed, DataGridView automatically replicates the changes to the bound list data source. Similarly, when changes are made to an item in the list data source of BindingList<T>, an item change notification is broadcast to all bound controls.

 

BindingList<T> allows us to use almost any class to create a data-binding-savvy strongly typed list data source. However, some item classes come already associated with their own collection classes. Although any collection class that implements IList can be used as a list data source, you don't get full-flavor data binding if you don't implement IBindingListnamely, support for two-way list and item change notification.

To gain this support and to avoid the highly involved implementation of IBindingList ourselves, we'd love to be able to "upgrade" an existing IList implementation to IBindingList. The class that performs this upgrade for you is BindingSource.

The BindingSource component (from System.Windows.Forms) consumes either item types or list types and exposes them as IBindingList implementations.

 

if you need to implement a VCR-type control to navigate the items in a data source, you don't have to acquire a BindingManager and you don't have to manually create your own navigation methods. Instead, you simply rely on the BindingSource to manage currency and use its currency-oriented methods as required:

 

void moveFirstButton_Click(object sender, EventArgs e)

{ this.employeesBindingSource.MoveFirst(); RefreshItems(); }

 

Master-Detail binding
image

 

Why [STAThread]

When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded. Without getting into a huge discussion about COM and threading, this attribute ensures the communication mechanism between the current thread and other threads that may want to talk to it via COM. When you're using Windows Forms, depending on the feature you're using, it may be using COM interop in order to communicate with operating system components. Good examples of this are the Clipboard and the File Dialogs.

SingleInstanceApplication

// SingleInstanceApplication.cs
class SingleInstanceApplication : WindowsFormsApplicationBase
{ ... protected override void OnCreateMainForm() { this.MainForm = new MainForm(); }

Friday, March 05, 2010 8:13:20 PM UTC  #    Comments [0]    |   |  Trackback
 Thursday, March 04, 2010

CLR and .NET Framework

The CLR is the runtime for executing managed code. C# is one of several managed
languages that get compiled into managed code. Managed code is packaged into an
assembly, in the form of either an executable file (an .exe) or a library (a .dll), along
with type information, or metadata.

Managed code is represented in Intermediate Language or IL. When the CLR loads
an assembly, it converts the IL into the native code of the machine, such as x86. This
conversion is done by the CLR’s JIT (Just-In-Time) compiler. An assembly retains

almost all of the original source language constructs, which makes it easy to inspect
and even generate code dynamically.

The CLR performs as a host for numerous runtime services. Examples of these services
include memory management, the loading of libraries, and security services.
The CLR is language-neutral, allowing developers to build applications in multiple
languages (e.g., C#, Visual Basic .NET, Managed C++, Delphi.NET, Chrome .NET,
and J#).

 

 

How the Garbage Collector Works:

The GC begins with its root object references, and walks the object graph, marking
all the objects it touches as reachable. Once this process is complete, all objects that
have not been marked are considered unused, and are subject to garbage collection.
Unused objects without finalizers are immediately discarded; unused objects with
finalizers are enqueued for processing on the finalizer thread after the GC is complete.
These objects then become eligible for collection in the next GC for the object’s
generation (unless resurrected).

 

The remaining “live” objects are then shifted to the start of the heap (compacted),
freeing space for more objects. This compaction serves two purposes: it avoids

memory fragmentation, and it allows the GC to employ a very simple strategy when
allocating new objects, which is to always allocate memory at the end of the heap.
This avoids the potentially time-consuming task of maintaining a list of free memory
segments.

 

If there is insufficient space to allocate memory for a new object after garbage
collection, and the operating system is unable to grant further memory, an
OutOfMemoryException is thrown.

 

Generational collection
The most important optimization is that the GC is generational. This takes advantage
of the fact that although many objects are allocated and discarded rapidly, certain
objects are long-lived and thus don’t need to be traced during every collection.
Basically, the GC divides the managed heap into three generations. Objects that have
just been allocated are in Gen0 and objects that have survived one collection cycle
are in Gen1; all other objects are in Gen2.

 

The large object heap
The GC uses a separate heap called the Large Object Heap (LOH) for objects larger
than a certain threshold (currently 85,000 bytes). This avoids excessive Gen0
collections—without the LOH, allocating a series of 16 MB objects might trigger a
Gen0 collection after every allocation.

The LOH is not subject to compaction, because moving large blocks of memory
during garbage collection would be prohibitively expensive. This has two
consequences:

1. Allocations can be slower
2. The LOH is subject to fragmentation

The large object heap is also nongenerational: all objects are treated as Gen2.

 

Concurrent and background collection

The GC must freeze (block) your execution threads for periods during a collection.
This includes the entire period during which a Gen0 or Gen1 collection takes place.
The GC makes a special attempt, though, at allowing threads to run during a Gen2
collection

 

Forcing Garbage Collection (not recommend)

GC.Collect()

 

A good guideline is to implement IDisposable yourself if any field in your class is assigned an object that implements IDisposable. (Such as System.Timers.Timer)(System.Threading.Timer is different)

 

Monitor the memory leaks: long memoryUsed = GC.GetTotalMemory (true);

 

Occasionally, it’s useful to hold a reference to an object that’s “invisible” to the GC
in terms of keeping the object alive. This is called a weak reference, and is implemented
by the System.WeakReference class.

 

One use for WeakReference is to cache large object graphs.
http://www.shafqatahmed.com/2008/01/weakreference-b.html

 

 

Asynchronous Methods

asynchronous programming model or APM

An asynchronous method aims never to block any thread, instead using a pattern of
returning with a callback.

 

The end goal of the APM is thread economy.

The purpose of asynchronous methods isn’t to
provide a convenient mechanism for executing a method in parallel with the caller;
it’s to optimize thread resources.

 

Here’s the golden rule of the APM: Make good use of the CPU, or exit with a callback!

 

The primary use for asynchronous methods is handling many potentially longrunning
concurrent requests—typically over slow network connections.

 

IAsyncResult BeginXXX (in/ref-args, AsyncCallback callback, object state);
return-type EndXXX (out/ref-args, IAsyncResult asyncResult);
public delegate void AsyncCallback (IAsyncResult ar);

 

To avoid blocking, you will nearly always call the EndXXX method from inside the
callback method. Callbacks always run on pooled threads.

 

image

 

http://en.csharp-online.net/CSharp_Delegates_and_Events%E2%80%94Asynchronous_method_calls
http://msdn.microsoft.com/en-us/library/h80ttd5f.aspx

Collections

ICollection Properties

image

image

IComparer
Copmare method

IEqualityComparer
GetHashCode, Equals

SortedList calss is a dictionary.

Race conditions and deadlocks

http://support.microsoft.com/kb/317723

A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable. Then the first thread and second thread perform their operations on the value, and they race to see which thread can write the value last to the shared variable. The value of the thread that writes its value last is preserved, because the thread is writing over the value that the previous thread wrote.

A deadlock occurs when two threads each lock a different variable at the same time and then try to lock the variable that the other thread already locked. As a result, each thread stops executing and waits for the other thread to release the variable. Because each thread is holding the variable that the other thread wants, nothing occurs, and the threads remain deadlocked.

Thursday, March 04, 2010 7:57:29 PM UTC  #    Comments [0]    |   |  Trackback
 Wednesday, March 03, 2010
 Tuesday, February 23, 2010
 Wednesday, January 27, 2010

Setting the value will force future processes in that space to use the specified .NET runtime, like:

set COMPLUS_Version = v3.5

That would force everything to run in .NET 3.5.

http://www.cookcomputing.com/blog/archives/000597.html

It is not necessary to rebuild NUnit. I discovered that if you add the following to the relevant NUnit application config file you can run a test dll built for .NET 4.0. Under <configuration> add:

<startup>
  <requiredRuntime version="v4.0.20506" />
</startup>

and under <runtime> add:

<loadFromRemoteSources enabled="true" />
Wednesday, January 27, 2010 3:49:24 PM UTC  #    Comments [0]    |   |  Trackback
 Monday, January 25, 2010

(By Eric Evan)

Chapter 1 What Is Domain-Driven Design

When we begin a software project, we should focus on the domain it is operating in. The entire purpose of the software is to enhance a specific domain.

How can we make the software fit harmoniously with the domain? The best way to do it is to make software a reflection of the domain.

The model is our internal representation of the target domain, and it is very necessary throughout the design and the development process.

There are different approaches to software design. One is the waterfall design method. This method involves a number of stages. The business experts put up a set of requirements which are communicated to the business analysts. The analysts create a model based on those requirements, and pass the results to the developers, who start coding based on what they have received. It’s a one way flow of knowledge. While this has been a traditional approach in software design, and has been used with a certain level of success over the years, it has its flaws and limits. The main problem is that there is no feedback from the analysts to the business experts or from the developers to the analysts. Another approach is the Agile methodologies, such as Extreme Programming (XP). These methodologies are a collective movement against the waterfall approach, resulting from the difficulties of trying to come up with all the requirements upfront, particularly in light of requirements change. It’s really hard to create a complete model which covers all aspects of a domain upfront. It takes a lot of thinking, and often you just cannot see all the issues involved from the beginning, nor can you foresee some of the negative side effects or mistakes of your design. Another problem Agile attempts to solve is the so called “analysis paralysis”, with team members so afraid of making any design decisions that they make no progress at all. While Agile advocates recognize the importance of design decision, they resist upfront design. Instead they employ a great deal of implementation flexibility, and through iterative development with continuous business stakeholder participation and a lot of refactoring, the development team gets to learn more about the customer domain and can better produce software that meets the customers needs.

 

The Agile methods have their own problems and limitations; they advocate simplicity, but everybody has their own view of what that means. Also, continuous refactoring done by developers without solid design principles will produce code that is hard to understand or change. And while the waterfall approach may lead to over-engineering, the fear of overengineering may lead to another fear: the fear of doing a deep, thoroughly thought out design.

 

Chapter 2 The Ubiquitous Language

A core principle of domain-driven design is to use a language based on the model. Since the model is the common ground, the place where the software meets the domain, it is appropriate to use it as the building ground for this language.

Building a language like that has a clear outcome: the model and the language are strongly interconnected with one another. A change in the language should become a change to the model.

 

 

Chapter 3 Model-Driven Design

A better approach is to closely relate domain modeling and design. The model should be constructed with an eye open to the software and design considerations. Developers should be included in the modeling process.

 

image

 

image

 

 

image

 

Entities: There is a category of objects which seem to have an identity, which remains the same throughout the states of the software. For these objects it is not the attributes which matter, but a thread of continuity and identity, which spans the life of a system and can extend beyond it. Such objects are called Entities.

 

Value Objects:  There are cases when we need to contain some attributes of a domain element. We are not interested in which object it is, but what attributes it has. An object that is used to describe certain aspects of a domain, and which does not have identity, is named Value Object.

It is highly recommended that value objects be immutable.
One golden rule is: if Value Objects are shareable, they should be immutable. Value Objects should be kept thin and simple. When a Value Object is needed by another party, it can be simply passed by value, or a copy of it can be created and given.

 

Services:

we discover that some aspects of the domain are not easily mapped to objects.  But there are some actions in the domain, some verbs, which do not seem to belong to any object. They represent an important behavior of the domain, so they cannot be neglected or simply incorporated into some of the Entities or Value Objects. When such a behavior is recognized in the domain, the best practice is to declare it as a Service. Such an object does not have an internal state, and its purpose is to simply provide functionality for the domain. The assistance provided by a Service can be a significant one, and a Service can group related functionality which serves the Entities and the Value Objects.

(For example, to transfer money from one account to another; should that function be in the sending account or the receiving account? It feels just as misplaced in either.)

There are three characteristics of a Service:
1. The operation performed by the Service refers to a domain concept which does not naturally belong to an Entity or Value
Object.
2. The operation performed refers to other objects in the domain.
3. The operation is stateless.

 

Modules: it is necessary to organize the model into modules. Modules are used as a method of organizing related concepts and tasks in order to reduce complexity.

Another reason for using modules is related to code quality. It is widely accepted that software code should have a high level of cohesion and a low level of coupling.

Two of the most used are communicational cohesion and functional cohesion.

 

 

Three patterns:  Aggregate is a domain pattern used to define object ownership and boundaries. Factories and Repositories are two design patterns which help us deal with object creation and storage.

 

An Aggregate is a group of associated objects which are considered as one unit with regard to data changes.

 

The root is an Entity, and it is the only object accessible from outside. The root can hold references to any of the aggregate objects, and the other objects can hold references to each other, but an outside object can hold references only to the root object.

Cluster the Entities and Value Objects into Aggregates and define boundaries around each. Choose one Entity to be the root of each Aggregate, and control all access to the objects inside the boundary through the root. Allow external objects to hold references to the root only. Transient references to internal members can be passed out for use within a single operation only.

 

Factories are used to encapsulate the knowledge necessary for object creation, and they are especially useful to create Aggregates. When the root of the Aggregate is created, all the objects contained by the Aggregate are created along with it, and all the invariants are enforced.
A Factory Method is an object method which contains and hides knowledge necessary to create another object.

 

There are times when a Factory is not needed, and a simple constructor is enough. Use a constructor when:
• The construction is not complicated.
• The creation of an object does not involve the creation of others, and all the attributes needed are passed via the constructor.
• The client is interested in the implementation, perhaps wants to choose the Strategy used.
• The class is the type. There is no hierarchy involved, so no need to choose between a list of concrete implementations.

 

 

 

Therefore, use a Repository, the purpose of which is to encapsulate all the logic needed to obtain object references.

The overall effect is that the domain model is decoupled from the need of storing objects or their references, and accessing the
underlying persistence infrastructure. Provide repositories only for Aggregate roots that actually need direct access. Keep the client focused on the model, delegating all object storage and access to the Repositories.

 

There is a relationship between Factory and Repository. They are both patterns of the model-driven design, and they both help us to manage the life cycle of domain objects. While the Factory is concerned with the creation of objects, the Repository takes care of already existing objects.

 

Chapter 4 Refactoring Toward Deeper Insight

 

One of the first things we are taught about modeling is to read the business specifications and look for nouns and verbs. The nouns are converted to classes, while the verbs become methods. This is a simplification, and will lead to a shallow model.

We start with a coarse, shallow model. Then we refine it and the design based on deeper knowledge about the domain, on a better understanding of the concerns. We add new concepts and abstractions to it. The design is then refactored. Each refinement adds more clarity to the design. This creates in turn the premises for a Breakthrough.

 

To reach a Breakthrough, we need to make the implicit concepts explicit.

The first way to discover implicit concepts is to listen to the language.

Try to see if there is a missing concept.

 

Another obvious way of digging out model concepts is to use domain literature.

 

There are other concepts which are very useful when made explicit: Constraint, Process and Specification.

Placing the Constraint into a separate method has the advantage of making it explicit.
Processes are usually expressed in code with procedures.
Simply said, a Specification is used to test an object to see if it satisfies a certain criteria. The domain layer contains business rules which are applied to Entities and Value Objects. Those rules are usually incorporated into the objects they apply to. When rule is not a simple method and spans many entities and value objects,  the rule should be encapsulated into an object of its own, which becomes the Specification of the Customer, and should be kept in the domain layer.

 

 

Chapter 5 Preserving Model Integrity

 

This chapter is about large projects which require the combined efforts of multiple teams.

 

Instead of trying to keep one big model that will fall apart later, we should consciously divide it into several models.

Each model should have a clearly delimited border, and the relationships between models should be defined with precision.

 

image

 

A model should be small enough to be assigned to one team.

 

Bounded Context: The main idea is to define the scope of a model, to draw up the boundaries of its context, then do the most possible to keep the model unified.
Explicitly set boundaries in terms of team organization, usage within specific parts of the application, and physical manifestations such as code bases and database schemas. Keep the model strictly consistent within these bounds, but don’t be distracted or confused by issues outside.

A Bounded Context is not a Module. A Bounded Context provides the logical frame inside of which the model evolves. Modules are used to organize the elements of a model, so Bounded Context encompasses the Module.

 

A Context Map is a document which outlines the different Bounded Contexts and the relationships between them. What it is important is that everyone working on the project shares and understands it.

 

A common practice is to define the contexts, then create modules for each context, and use a naming convention to indicate the context each module belongs to.

 

The purpose of the Shared Kernel is to reduce duplication, but still keep two separate contexts.

 

Core Domain and Generic Subdomain

 

Last Chapter

 

Keep in mind some of the pitfalls of domain modeling:
1) Stay hands-on. Modelers need to code.
2) Focus on concrete scenarios. Abstract thinking has to be anchored in concrete cases.
3) Don't try to apply DDD to everything. Draw a context map and decide on where you will make a push for DDD and where you will not. And then don't worry about it outside those boundaries.
4) Experiment a lot and expect to make lots of mistakes. Modeling is a creative process.

Monday, January 25, 2010 9:54:21 PM UTC  #    Comments [0]    |   |  Trackback
 Friday, January 15, 2010

http://referencesource.microsoft.com/serversetup.aspx

Configuring Visual Studio for Debugging

Set Up Visual Studio 2008:

a. Install and set up Visual Studio 2008 including any updates.

Set Up the Symbols Path:

a. Launch Visual Studio 2008.
b. From the Tools menu, choose Options.
c. In the Options dialog box, open the Debugging node and select General
        a. Clear 'Enable Just My Code (Managed only)'
        b. Check 'Enable source server support'

d. Select Symbols under Debugging.
e. In the Symbol File Locations box, add the following location:
   http://referencesource.microsoft.com/symbols

   Note: To add the Symbols path Click folder icon.
f. Enter in text box under 'Cache symbols from symbol servers to this directory:' C:\Symbols\RSCC:
   Note : If C:\Symbols is already in use then you can chose another folder name. The folder name must be input into the
   text box
g. Click OK.

Debugging your Application

a. Open your application code solution and build the solution.
b. Set a break point in the code.
c. Start debugging (press F5).
d. EULA pops up, click Accept.
e. Source code will be downloaded.

Friday, January 15, 2010 9:14:56 PM UTC  #    Comments [0]    |  Trackback
 Thursday, January 14, 2010

Model-View Architecture

image

Three-Tie Architecture

image

Model-View-Controller Architecture

image

image

image

 

The preceding test is a unit test, because it tests just one isolated component: AdminController.
It doesn’t rely on any real implementation of IMembersRepository, and so it doesn’t need to
access any database.

 

When you deliberately chain together a series of components and test them together,
that’s an integration test.

 

image 

image

image

image

image

Thursday, January 14, 2010 10:35:20 PM UTC  #    Comments [0]    |  Trackback
 Thursday, October 29, 2009

http://www.asp.net/learn/mvc/tutorial-08-cs.aspx

http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/

Instead of using the registermvc.wcf script, you can add a new extension to IIS that is mapped to the ASP.NET framework by hand. When adding a new extension yourself, make sure that the checkbox labeled Verify that file exists is not checked.

Thursday, October 29, 2009 3:52:05 PM UTC  #    Comments [0]    |   |  Trackback
 Monday, October 19, 2009

The BackgroundWorker class is built on top of ThreadPool and adds many features for interthread communication.

The single most important issue you must deal with is exceptions in your WaitCallback, the method that does the work in the background thread. If any exceptions are thrown from that method, the system will terminate your application. It doesn't simply terminate that one background thread; it terminates the entire application. This behavior is consistent with other background thread API methods, but the difference is that QueueUserWorkItem doesn't have any built-in capability to handle reporting errors.

In addition, QueueUserWorkItem does not give you any built-in methods to communicate between the background threads and the foreground thread. It doesn't provide any built-in means for you to detect completion, track progress, pause tasks, or cancel tasks. When you need those capabilities, you can turn to the BackgroundWorker component, which is built on top of the QueueUserWorkItem functionality.

 

For most common synchronization problems, examine the Interlocked class to see whether you can use it to provide the capabilities you need. With many single operations, you can. Otherwise, your first choice is the lock() statement. Look beyond those only when you need special-purpose locking capability.

 

Two of the most widely used locking techniques are just plain wrong when seen from that viewpoint. lock(this) and lock(TypeOf(MyType)) have the nasty effect of creating your lock object based on a publicly accessible instance.

 

When you decide what to lock, pick a private field that's not visible to any callers. Do not lock a publicly visible object. Locking publicly visible objects requires that all developers always and forever follow the same practice, and it enables client code to easily introduce deadlock issues.

 

No matter how it happens, the pattern is similar. Your class acquires a lock. Then, while still in the synchronized section, it invokes a method that calls code beyond your control. That client code is an open-ended set of code that may eventually trace back into your class, even on another thread. You can't do anything to prevent that open-ended set of code from doing something that might be evil. So instead, you must prevent the situation: Don't call unknown code from inside locked sections of your code.

Let's summarize what you've learned about InvokeRequired. Once your controls are created, InvokeRequired is reasonably fast and always safe. However, if the target control has not been created, InvokeRequired can take much longer, and if none of the controls has been created, InvokeRequired takes a long time to give you an answer that's probably not even correct. Even though Control.InvokeRequired can be a bit expensive, it's still quite a bit cheaper than a call to Control.Invoke when it's not necessary. In WPF, some of the edge cases have been optimized and work better than they do in the Windows Forms implementation.

Invoke and InvokeRequired do quite a bit of work on your behalf. All this work is required because Windows Forms controls are built on the single-threaded apartment model. That legacy behavior continues under the new WPF libraries. Underneath all the new .NET Framework code, the Win32 API and window messages are still lurking. That message passing and thread marshaling can lead to unexpected behavior. You need to understand what those methods do and work with their behavior.

Monday, October 19, 2009 9:30:23 PM UTC  #    Comments [0]    |  Trackback
 Thursday, October 15, 2009

Chapter 1 : Working with Generics.

   1:  public class EmployeeComparer : EqualityComparer<Employee>
   2:  {
   3:      public override bool Equals(Employee x, Employee y)
   4:      {
   5:          return EqualityComparer<Employee>.Default.Equals(x, y);
   6:      }
   7:   
   8:      public override int GetHashCode(Employee obj)
   9:      {
  10:          return EqualityComparer<Employee>.Default.
  11:              GetHashCode(obj);
  12:      }
  13:  }

 

The Default property examines the type argument, T. If the type implements IEquatable<T>, then Default returns an IEqualityComparer<T> that uses the generic interface. If not, Default returns an IEqualityComparer<T> that uses the System.Object virtual methods Equals() and GetHashCode(). In this way, EqualityComparer<T> guarantees the best implementation for you.

 

 

public delegate void Action<T>(T obj);
   1:  public static void EnumerateAll<T>(this IEnumerable<T>
   2:  theCollection, Action<T> doIt)
   3:  {
   4:      foreach (T thing in theCollection)
   5:          doIt(thing);
   6:  }

 

delegate bool Predicate<T>(T obj)

   1:  public IEnumerable<T> Test<T> (IEnumerable<T> theCollection,
   2:  Predicate<T> test)
   3:  {
   4:      foreach (T source in theCollection)
   5:          if ( test( source ) )
   6:              yield return source;
   7:  }

 

public delegate void EventHandler<TEventArgs>(
    object sender, TEventArgs args)
    where TEventArgs: EventArgs

Now you can define a event like this
public event EventHandler<MyEventArgs> OnRaiseMyEvent;
Performance of boxing of unboxing
1. A new object must be allocated on the managed heap.
2. The value of the stack-based data must be transferred into that memory location.
3. When unboxed, the value stored on the heap-based object must be transferred back to the stack.
4. The now unused object on the heap will (eventually) be garbage collected.
   1:  public static T FirstOrDefault<T>(this IEnumerable<T> sequence,
   2:      Predicate<T> test)
   3:  {
   4:      foreach (T value in sequence)
   5:          if (test(value))
   6:              return value;
   7:   
   8:      return default(T);
   9:  }

 

 

1: public delegate T FactoryFunc<T>();

   2:  public static T Factory<T>(FactoryFunc<T> makeANewT)
   3:      where T : new()
   4:  {
   5:      T rVal = makeANewT();
   6:      if (rVal == null)
   7:          return new T();
   8:      else
   9:          return rVal;
  10:  }
 Ensure your generic classes support disposable type parameters
   1:  public void GetThingsDone()
   2:  {
   3:      T driver = new T();
   4:      using (driver as IDisposable)
   5:      {
   6:          driver.DoWork();
   7:      }
   8:  }
 
If drive is a property member in the generic class, you have to implement IDisposable interface. So better to
take it out from generic class.
   1:  public class EngineDriver<T> where T : IEngine
   2:  {
   3:      private T driver;
   4:      public EngineDriver(T driver)
   5:      {
   6:          this.driver = driver;
   7:      }
   8:   
   9:      public void GetThingsDone()
  10:      {
  11:          driver.DoWork();
  12:      }
  13:  }

Use Delegates to define method constrains on Type Parameters
When it's unwieldy to use an interface to define a constraint, you can define a method signature and a delegate type that suits your needs. Then you add an instance of that delegate to the list of the parameters of the generic method. The developers using your class can use a lambda expression to define that method, writing much less code, in a much clearer fashion. Developers using your class need to create the lambda expression that defines the method functionality they need. There's no extra code to support the syntax of interface-based constraints.

   1:  public static class Example
   2:  {
   3:      public static T Add<T>(T left, T right,
   4:          Func<T, T, T> AddFunc)
   5:      {
   6:          return AddFunc(left, right);
   7:      }
   8:  }

In the general case, any method your generic class needs to call can be replaced by a specific delegate.

It's not a good idea to create generic specializations for base classes when you intend to support the class and all its descendents.
(That is to say: don’t create a same name generic method in a class as the names in base classes or derivative classes))

If a type needs type-level data members, especially data members involving the type parameter, make it a generic class. Otherwise, use generic methods.
Obviously, not every generic algorithm is suited for generic methods instead of a generic class. Some simple guidelines can help you determine which to use. In two cases you must make a generic class: The first occurs when your class stores a value of one of the Type parameters as part of its internal state. (Collections are an obvious example.) The second occurs when your class implements a generic interface. Except for those two cases, you can usually create a nongeneric class and use generic methods. You'll end up with more granularity in your options for updating the algorithms in the future.

One common problem for many developers is how to create a method signature for methods that logically return more than one item. Many developers turn to ref or out parameters in those cases. But it's better to define generic tuples that can return multiple discrete values. A tuple is nothing more than a composite with n elements.

   1:  public struct Tuple<T1, T2> : IEquatable<Tuple<T1, T2>>
   2:  {
   3:      private readonly T1 first;
   4:      public T1 First
   5:      {
   6:         get { return first; }
   7:      }
   8:   
   9:      private readonly T2 second;
  10:      public T2 Second
  11:      {
  12:          get { return second; }
  13:      }
  14:   
  15:      public Tuple(T1 f, T2 s)
  16:      {
  17:          first = f;
  18:          second = s;
  19:      }
  20:      // Implementation of IEquatable<Tuple<T1, T2>> elided
  21:  }

 

   1:  public static Tuple<string, decimal> FindTempForNearestCity
   2:      (string soughtCity)
   3:  {
   4:      string city = "algorithmElided";
   5:      decimal temp = decimal.MinValue; // really cold.
   6:      return new Tuple<string, decimal>(city, temp);
   7:  }
Thursday, October 15, 2009 9:31:11 PM UTC  #    Comments [0]    |  Trackback
 Wednesday, October 14, 2009

in AssemblyInfo.cs
[Assembly:ScriptResource(“Calculator.Resources.Calculator.js”,”Calculator.Resources.MessageResources”,"Messages”)]

When you configure an AJAX-enabled ASP.NET Web site, use only the default value of UseCookies for the cookieless attribute. Settings that use cookies encoded in the URL are not supported by the ASP.NET AJAX client script libraries.

use load event to load view data, use preRender event to save view data

<trace enabled=”true” pageOutput=”false” localOnly = “true” />

Custom server controls that use control state must call the RegisterRequiresControlState method on each request because registration for control state is not carried over from request to request during a postback event. It is recommended that registration occur in the Init event.

System.Web.Management.WebAuditEvent for Security-related Web Events.
System.Web.Management.WebErrorEvent for Web Events caused by problems with configuration or application code.

aboutPostBack(): Cancel the postback that is currently running
args.set_cancel(true) Cancel this postback

AJAX add error handler code by pageMgr.add_endRequest(errorHandler);
Raised after the response for an asynchronous postback is processed and the page is updated, or during the processing of the response if there is an error. If an error occurs, the page is not updated. Use this event to provide customized error notification to users or to log errors.

Override Evaluate(HttpContext context, Control control) in custom parameter for commands.

Request.ServerVariables[“REMOTE_ADDR”]

Wednesday, October 14, 2009 4:03:20 AM UTC  #    Comments [0]    |  Trackback
 Tuesday, October 13, 2009

Use ScriptManager.RegisterDataItem method to send data from the server to the client during asynchronous postbacks, regardless of whether the control receiving the data is inside an UpdatePanel control.
Use REgisterAsyncPOstBackControl for registers a control as a trigger for asynchronous postbacks.

abortPostBack(): Cancel the postback that is currently running
args_set_cancel(true): Cancel this postback

The partial page postback is managed on the client-side by the PageRequestManager object. Whenever a partial page postback is initiated, the PageRequestManager object performs the following client-side actions:
http://www.4guysfromrolla.com/demos/printPage.aspx?path=/articles/052808-1.aspx

  1. The initializeRequest event is raised - this is the first event raised during the partial postback life-cycle and affords us an opportunity to determine the HTML element that triggered the postback and cancel the postback, if needed.
  2. The beginRequest event is raised - this event is raised just before the request is sent to the server. The UpdateProgress control uses this event to displayed it's output.
  3. The request is sent to the server and the page is re-rendered there.
  4. The pageLoading event is raised when the server returns its response.
  5. The pageLoaded event is raised. This event is raised whenever the content on the page is refreshed, be it via a full page postback or a partial page postback.
  6. The endRequest event is raised, signalling completion of the partial page postback lifecycle.

DataSourceID in <asp:BulletedList .. />

<httpHandlers> <add verb=”*" path=”*.media” validate=”false” type=”Contoso.Web.UI.MultimediaDownloader” /></httpHandlers>
If the Validate property is false, ASP.NET will not attempt to load the class until the actual matching request comes, potentially delaying the error but improving the startup time.

$Create shortcut method
Provides a shortcut to the create method of the Sys.Component class.

$get
$get can be used as shorthand for the document.getElementById and element.getElementById functions.  The $get shortcut function points to the Sys.UI.DomElement.getElementById JavaScript function which is defined as part of the ASP.NET AJAX client side library (which means you will need to include a ScriptManager on the page to be able to use it).  $get accepts two parameters, the first is the ID of the DOM element you want to retrieve, the second is the parent element of where the search starts.  The second parameter is optional and when it is not supplied defaults to the document element.

$find
The $find shortcut function allows you to look up an ASP.NET AJAX client side Component by it's ID.  Here is a link to the $find shortcut's documentation and below is the API description.

Template.InstantiateIn(control c)

<asp:AsyncPostBackTrigger> and <asp:PostBackTrigger> childrenAsTriggers = true;

LoadViewState :control developers can override this method to specify how a custom server control restores its view state. For more information, see ASP.NET State Management Overview.

public bool HasCapability(
    string delegateName,
    string optionalParameter
)

DataKeyNames property in asp:DetailsView

ASP.NET session state supports several different storage options for session data. Each option is identified by a value in the SessionStateMode enumeration. The following list describes the available session state modes:

  • InProc mode, which stores session state in memory on the Web server. This is the default.

  • StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

  • SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

  • Custom mode, which enables you to specify a custom storage provider.

  • Off mode, which disables session state.

 
http://msdn.microsoft.com/en-us/library/hkx121s4.aspx
<system.web>
  <deviceFilters>
    <filter
      name="capability"
      compare="capabilityName"
      argument="argument" />
    <filter
      name="capability"
      type="className"
      method="methodName" />
  </deviceFilters>
</system.web>
<mobile:Image runat=server ImageURL="bw.gif">
  <DeviceSpecific>
    <Choice Filter="isColor" ImageURL="colorImg.gif"
      AlternateText="This device cannot display the image." />
    <Choice Filter="isWML11" ImageURL="myImage.wbmp" />
    <Choice ImageURL="monoImage.gif" />
  </DeviceSpecific>
</mobile:Image>

 

If the filter name is omitted, the choice is selected by default.

ScriptManager.RegisterClientScriptBlock(txtInfo, typeof(TextBox), “txtInfo_Script”, generatedScript, false);

Disable Request Validation
<%@ Page validateRequest=”false” %>

a new validation control ovverrides the EvaluateIsValid method to validate the value of the related control.

HttpContext.RewritePath method redirects a request for a resource to another resource without changing the URL.
S
Redirects a request for a resource to a different path than the one that is indicated by the requested URL. RewritePath is used in cookieless session state to strip session IDs from URLs.

Response.Redirect will have 2 request from client browser. Server.Transfer is 1 request and will not change the path in the browser.

Use Style defined in StyleSheet control
<mobile:Label ID=”MyLabel” Runat=”server” StyleReference=”MyStyleSheet:StyleA”> </mobile:Label>

<Compilation debug=”false” Batch=”true”>
debug=false (optimize the performance)
batch=”true” (default, ensure that during the initial request to the application, the code-behind files for the Web pages are compiled.
If True, eliminates the delay caused by the compilation required when you access a file for the first time. When this attribute is set to True, ASP.NET precompiles all the uncompiled files in a batch mode, which causes an even longer delay the first time the files are compiled. However, after this initial delay, the compilation delay is eliminated on subsequent access of the file.

Tuesday, October 13, 2009 9:19:49 PM UTC  #    Comments [0]    |  Trackback
 Thursday, October 08, 2009

ProfileOnMigrateAnonymous(…)

4 types of authentication: Windows, forms, passport anonymous
<deny users=”?" /> and <allow users=”*" />
FormsAuthentication.Authenticate
FormsAuthentication.RedirectFromLoginPage(…)
FormsAuthentication.SignOut()

SeesionState in mobile website
<sessionState cookieless=”true”/>
<mobileControls cookielessDatadictionaryType=”System.web.Mobile.CookielessData” />

User-Agent HTTP header
browserCaps relies on XML files that contain a hierarchal structure of browser definitions. The default location is at .net framework folder .\CONFIG\Browser
ASP.BrowserCapsFactory.dll and HttpBroserCapabilities class
Request.Browser.IsMobileDevice

Search Target machine and launch conditions
Pregrouped Launch Conditions

MSI command-line options.

The Copy Web tool doesn not merge changes within a single file; it only does complete file copies.

By default, a Web Setup Project checks for an IIS version later than 4.

Precompiling Web Applications.

Application caching
The cache object is available as a property of the Page object.
absoluteExpiration and slidingExpiration
onRemoveCallback
CacheDependency and AggregateCacheDependency
Cache.Insert(“FileCache”, “CacheContents”, new System.Web.Caching.CacheDependency(Server.MapPath(“SourceFile.xml”)))

Page output caching
With page output caching, ASP.NET can keep a copy of a rendered ASP.NET Web page in memory on the server.
<%@ OutputCache Duration=”15” VaryByParam=”location;count” %>
Use REspoinse.Cache object to do the run-time decision about output caching
Response.WriteSubstitution method and Subsitution control (with MethodName property)
HttpValidationStatus and Response.Cache.AddValidationCallback to invalidate the page output caching if needed.
Add CacheProfile in Web.config and then reference it in page
<%@ OutputCache CacheProfile=”One MInuteProfile” VaryByParam=”none” %>

Thursday, October 08, 2009 8:16:02 PM UTC  #    Comments [0]    |  Trackback
 Wednesday, October 07, 2009

The templated user control can be used to provide data that is to be rendered but allows the Web page designer to specify the format of the data.

A custom Web control is a control that inherits from a WebServer control. It can be compiled into a dll and put to GAC.
To create a custom version of existing control. YOu need to override the Render method and use HtmlTextWriter to output your display information.

Add icon to your control [ToolboxBitmap(typeof(LabeledTextbox), “MyUserControls.LabeledTextBox.bmp”)]

[DefaultProperty(“PromptText”)]
public class LabeledTextBox : TextBox

Use ToolboxDataAttribute to control the the Markup generated for your Custom Control. Also use [assembly: TagPrefix(“MyUserControls”, “muc”0] to change the prefix.

Create a Custom Designer for a Custom Control (p693)

Composite control inherits from CompositeControl class and overrides the CreateChildControls method. It has no designer screen.

Page_Error event handler
Server.GetLastError().Message
Server.ClearError()

Application_Error event handler and Server.Transfer

WebConfigurationManager
GetSection
GetSectionGroup

Asynchronous Web Page
Async attribute in Page declarative
Create event to start and end your asynchronous code (BeginProcessRequest, EndProcessRequest)
AddOnPreRenderCompleteAsync(bh, eh)

Customize hander should implement IHttpHandler
IsResuable property and ProcessRequest method

Request.Browser HttpBrowserCapabilities
Page.Header

<%@ Page Debug=”true” … %>
We can define specific page for various HTTP status codes
Remote Debugging Monitor (Msvsmon.exe)

<%@ Page trace=”true” … />
View Trace data on a virtual page named Trace.axd

Sys.Debug for AJAX client debugging

ASP.NET health monitoring

Local Resource file: <PageName>.aspx.<LanguageId>.resx
meta:resourcekey
Language preference option in Browser

Global Resources
<%$ Resources:LocalizedText, Greeting %>
Label1.Text = Resources.LocalizedText.Greeting;
Store local resources in the App_LocalResources folder

To localize static text that is not part of a control, you can either convert it to a control or use the Localize control. It functions much like the Literal control.
GetLocalResourceObject method and GetGlobalResourceObject method.
Global resources should be stored in the App_GlobalResources folder

<div style=’height: expression(document.body.clientHeight / 2); width: expression(document.body.clientWidth / 2); ‘>
Culture: This object determines the results of culture-dependent functions, such as the date, number, and currency formatting. You can only define the Culture object with specific cultures that define both language and regional formatting requirements. You can not define the Culture object with neutral cultures that define only a language.
UICulture This property determines which global or local resources are loaded for the page. You can define UICulture with either neutral or specific cultures.

You define the Culture and UICulture properties by overriding the page’s InitializeCulture method.
CultureInfo.GetCultures(CultureTypes enumeration)
<globalization uiculture=”es” culture=”es-MX” />
<%@ Page uiculture=”es” culture=”es-MX” %>

Wednesday, October 07, 2009 8:52:21 PM UTC  #    Comments [0]    |  Trackback

The ObjectDataSource control is responsible for the lifetime of the object. It creates it and dispose of it. Therefore, the business layer code should be written in a stateless manner. Alternatively, if the business layer uses static methods, the ObjectDataSource an use these methods without creating an instance of the actual business object.

DataObject and DataObjectMethod attributes.

SqlDataSource can work with ODBC and OLE DB
SQlDataSource.DataSourceMode

SiteMapDataSource: StartingNodeUrl, ShowStartingNode, StartFromCurrentNode, StartingNodeOffset

<%# Eval(“Vin”) %>
<%# Eval(“Price”, “{0:C}”) %>
Eval is one-way (read-only) data binding

AppendDataBoundItems in ListControl can be used to keep all items that are currently in the ListControl in addition to appending the items from the data binding.

The DetailsView does not directly support sorting, whereas the GridView does.. GirdView does not automatically support inserting new records, whereas the DetailsView does support this feature.

Like the DetailsView, the FormView control is used to display a single record from a data source. However, the FormView control can allows developers to create templates that define how the data should be displayed.

FormView supports mutiple templates while Repeater control only support ItemTemplate.

ASP.NET Web Service : Set the Web service’s generated client proxy’s Credentials property to the newly created CredentialCache object.

WCF is a unifying programming model. It is meant to define a singular way for writing services and thereby unify things like Web services(.asmx), .Net Remoting, Message Queue (MSMQ), Enterprise Services (COM+), and Web Services Enhancements (WSE). It doesn’t replace these technologies on a individual basis. Instead, it provides a single programming model that you can use to take advantage of all of these items at once. With WCF, you can create a single service that can be exposed as HTTP, TCP, named pipes, and so on. You also have multiple hosting options.

EndPoint = A (address) + B (binding) + C (contract)
You can edit the WCF configuration information by using Service Configuration Editor (right click Web.config and choose Edit Wcf Configuration)

Wednesday, October 07, 2009 1:51:44 PM UTC  #    Comments [0]    |  Trackback
 Tuesday, October 06, 2009

use SqlMetal.exe to generate DBML file and code file
use XmlReaderSettings and XmlReader.Create to validate XML

Tuesday, October 06, 2009 2:29:55 AM UTC  #    Comments [0]    |  Trackback
 Monday, October 05, 2009

DataRow has a RowState property: Detached, Added, Unchanged, Modified, Deleted
Holding multiple copies of data with the DataRowVersion: Current, Default, Original, Proposed
Resetting the RowState with AcceptChanges and RejectChanges
Explicit changing RowState with the SetAdded and SetModified methods
DataTable.Copy will copy both schema and data while DataTable.Clone will only copy schema.
Importing DataRow Object into a DataTable

Dataview is seeentially an index collection.

DataSet contains a collection of DataTable and DataRelation bojects.
XmlWriteMode.DiffGram

aspnet_regiis –pef “ConnectionStrings” “C”\..\EncryptWebSite”
aspnet_regiis –pdf “ConnectionStrings” “C”\..\EncryptWebSite”

DataReader rdr = cmd.ExecuteReader();
DataTable publishers = new DataTable();
publishers.Load(rdr, LoadOption.Upsert)

Using multiple Active Result Sets (MARS) to execute multiple commands on a connection.

DBProviderFactory class
ProviderList = System.Data.Common.DbProviderFactories.GetFactoryClasses();
Enumerate Data Sources
DataTable sources = factory.CreateDataSourceEnumerator().GetDataSources();

Catch DBException
The connection classes contain an event called InfoMessage that can be used to retrieve general and error information from the database.

IAsyncResult object’s AsyncWaitHandle property was used to wait until the command finished executing.

To read BLOB data, the ExecuteReader method should be executed with the CommandBehavior.SequentialAccess parameter.
Also it needs to use reader.GetBytes(..) to read data.
TEXTPTR function and UPDATETEXT Command

Monday, October 05, 2009 9:30:50 PM UTC  #    Comments [0]    |  Trackback
 Friday, October 02, 2009

Page.ViewState property provides a dictionary object for retaining values between multiple requests for the ame page. The object is of the type StateBag.  Hidden field __ViewState. The view state includes a message authentication code (MAC). Or you can use ViewStateEncryptionMode property of the Page object to protect the viewstate.

Set to ControlEnableViewState to false to improve the performance on the large data input form. (data state and control state)
Control state allows you to store property value information that is specific to a control. This state cannot be turned off and therefore should not be used in lieu of view state. (Override OnInit, call Page.RegisterRequiresControlState method, override the SaveControlState mthod)

Hidden Fields control only store informaiton for a single page. Ti has no built-in compression, encryption, hashing, or chunking. It only works with HTTP POST.

Cookie’s Path and Domain propoerty.
Response.Cookies[“Info”][“FirstName”].value = “Tony”; //store multiple values in a Cookie

Should validate the query string. Also you should always encode cookie or query string values using Server.HtmlEncode before displaying the value in an HTML Web page to any user. (System.Web.HttpRequestValidationException)

Data Stored in the Application is not permanent. It is temporarily held in memory on the server.

The ASP.NET Application Life Cycle Page209

Implemente HttpApplication events by adding a Global.asax file

ASP.NET writes a cookie to the client’s machines to track their session. This cookie is called ASP.NET_SessionId and contains a random 24-byte value. Requests submit this cookie from the browser and ASP.NET maps the cookie’s value to the session on the server.

<SessionState mode=”off”/>  in web settings
EnableSessionState=”False” in page
<SessionStte cookieless=”true” …/> in web settings.
Session_Start and Session_End events.
Session State Mode: InProc, SateServer, SQLServer, Custom, Off

Profile properties are persisted in a database on a per-user basis and not stored in memory on a server.

You can define a master page to work at the folder level within your site.
Referencing Master Page Properties and Controls from Content Pages. P237

Global Theme for all sites in your domain
To apply a theme programmatically, set the page’s Theme property in the Page_PreInit method.

Web Parts are components of predefined fuctionality that can be embedded in a Web page.
Web Parts in ASP.NET require the ASP.NET personalization database (ASPNETDB)
The display mode is set using the SupportedDisplayModes collection.
Web Parts personalization relies on client-side cookies. It uses these cookies to look up setting sin the ASPNETDB.
Shared Personalization

ScriptManager and ScriptManagerProxy
UpdateMOde and ChildrenAsTrigger property of UpdatePanel
AsyncPostBackTrigger of UpdatePanel

AsyncPostBackError event of ScriptManager
abortPOstBack method of the PageRequestManager class

Page.ClientScript.RegisterClientScriptBlock; RegisterClientScript; RegisterONSubmitStatement

Only script registered with the ScriptManager are available for use in partial-page update scenarios. If you need your script in these scenarios you must resiger it with the Script-Manager class.

Creating own Client Callbacks
Server-Side
1. Implement the System.Web.UI,ICallbackEventHandler for your ASP.NET page.
2. Implement the RaiseCallbackEvent method
3. Implement the GetCallbackResult method
In Page_Load
1. Register the name of the client-side function by using Page.ClientScript.GetCallbackEventReference
2. Define a function used by the client to call the server and register it by using RegisterClientScriptBlock

Loaded script: Call the notifyScriptLoaded method of the Sys.Application object to tell the AJAX library once you have finished loading your script.

AJAX Client-Side Life Cycle Events:
Application: Init, load, unload, disposing
PageRequestManager: initialiizeRequest, beginRequest, pageLoading, pageLoaded, endRequest

When working with JavaScript files in the code editor, you can add a reference to the AJAX Library. This will ensure your coding gets IntelliSense for the library. This is similar to the using statement in c# and the imports statement in Visual Basic. You embed this reference in a comment at the top of your .js file. The following shows a example:
/// <reference anme=”MicrosoftAjax.js” />

Friday, October 02, 2009 1:57:55 PM UTC  #    Comments [0]    |  Trackback
 Wednesday, September 30, 2009

image

View state is not stored by the server. It is saved into the page’s view state and sent in the page’s response back to the user.

Page Life Cycle Events: PreInit->Init->InitComplete->Load->Control(PostBack) events->LoadComplete->PreRender->SaveStateComplete->Render->Unload

HTML vs Web Server Control

DIV tag’s InnerText and InnerHtml property

Any postponed event (an event triggered by a user that does not cause an automatic PostBack) executes before the actual event that caused the PostBack.  
AutoPostBack property

Control c = FindControl(“lblMessage”);

Use HttpUtility.HtmlEncode or the Server.HtmlEncode method to encode the untrusted data prior to placing it the Text Property of the controls.

Button control can be rendered as a submit button or a command button. Command button is one of a set of buttons that work together as a group, such as a toolbar. When clicked, Command event is called on the server. This event is passed an instance of CommandEVentArgs as a parameter.

Use the CheckBoxList control to create group of CheckBox controls. Same to RadioButtonList

Label is rendered as a <span> tag.
Literal control is not inherited from WebControl and mainly used to add text to the output of the page dynamically (from server)
Literal Mode Property: PassThrough, Encode, Transform

The Image control does not have a Click event. In situations in which a click event is necessary, you can use ImageButton or ImageMap instead. ImageMap allows you to define regions or “hot spots” that cause a PostBack.
If you set the HOtSpotMode on the HotSpot and the ImageMap, the HotSpot takes precedence.

Use Calendar control to show the schedule. (DayRender event)

Panel control generates a <div> element inside the browser.

MultiView and View Controls are meant to work together.
ACtiveViewIndex property and SetActiveView method. (Usually we use command buttons for navigation)

Xml control is used to display the contents of an XML document  with Extensible Stylesheet Language(SXL) transform.

Validators property of Page class. ASP.NET calls the Validate method automatically after the page’s Load event handler method executes. You need to check the IsValid property in every event handler to determine whether the code should run;
EnableClientScript property and SetFocusOnError
Set control’s CausesValidation to false to prevent Client-Side Validation.
ValidationGroup

Custom Client-Side Validation : function ClientFunctionName(source, arguments)
Attach the client-side function to a CustomValidator by setting the ClientFunctionName property of the CustomValidator control to the name of your validation function
Custom Server-Side Validation: Override its ServerValidate event(source, args)

Page Navigation: Client-side navigation;Cross-page posting;Client-side browser redirect;Server-side transfer
Cross-page posting: Set PostBackUrl, Page, use PreviousPage property, use PreviousPage.FindControl method or access strongly typed data directly.
Client-Side Browser Redirect: Use Response.Redirect (the redirect is accomplished by sending a Http response code of (302) to the browser along with the URL) (URL in address bar will change) (Can not access the PreviousPage property)
Server-Side Transfer: Page.Server.Transfer method. It Tranfer the entire context of a Web page over to another page (URL in address bar will not change) (You can access the PreviousPage property)

Wednesday, September 30, 2009 9:33:08 PM UTC  #    Comments [0]    |  Trackback

HTTP Verbs: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, DEBUG
                   LOCK AND UNLOCK (ONLY WITH DAV)

DAV: Disributed Authoring and Versioning. It is a set of extensions to HTTP/1.1

HTTP/1.1 200 ok   200 is the status code.
1xx: Informational  2xx: Success   3xx: Redirect Command   4xx: Client Error 5xx: Server Error

Get and Post: Get append the form data to the URL as part of the query string. Post put the form data into the message body of the request.

Assemblies in the Bin folder are automatically referenced in web application.

ASPX page = Page directives + Code + Page Layout

Dynamically compilation and pre-compilation (only in 2008)

FTP passive and active mode. (passive is more firewall friendly)

.SUO file: User option file.
It is best to keep the solution files in an independent folder.

Root Default Web.config file is located in the same directory as the Machine.config file.

WSAT: Web Site Administration Tool

Wednesday, September 30, 2009 3:08:37 AM UTC  #    Comments [0]    |  Trackback
 Saturday, September 26, 2009

PrintDocument.BeginPrint event, set the position of the streamToPrint.BaseStream property to 0.

chkIsManager.DataBindings.Add(“Checked”, ds, “Users.IsManager);

DataRowVersion.Original

Thread.Enter and Exit to lock object for reading and writing.

SuspendLayout and ResumeLayout http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout.aspx

XmlReader is more timeefficient than XmlDocument and Linq to XML

SafePrinting (PrintingPermissionLevel enumerations)

Call the endInvoke method in callback method

Saturday, September 26, 2009 8:12:28 PM UTC  #    Comments [0]    |  Trackback

Load assembly on demand http://msdn.microsoft.com/en-us/library/ms228997.aspx
1. Mark each dependency in Certkiller App1.exe.manifest as optional
2. Create an event handler for the AppDomain.ResourceResolve event named ResolveAssembly
3. In the ResolveAssembly event hander, call ApplicationDeployment.DowloadFiles and pass in the name of the assembly you want.

Databinding master-detail datagrid
Set the DataMember property of the child DataGridView to the name of the data relation.

Use SystemEvents.UserPreferenceChanged to deal with accessibility change event

ToolStripControlHost http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripcontrolhost.aspx

Saturday, September 26, 2009 4:37:50 AM UTC  #    Comments [0]    |  Trackback
 Friday, September 25, 2009

AccessibleStates
http://msdn.microsoft.com/en-us/library/system.windows.forms.accessiblestates.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.accessibleobject.aspx

Transitive property of installation package

Set the InstallerClass property of your custom action to False when you want to add a standard Console application at the end of the installation process

SqlDependency is ideal for caching scenarios, where your ASP.NET application or middle-tier service needs to keep certain information cached in memory. SqlDependency allows you to receive notifications when the original data in the database changes so that the cache can be refreshed.

To set up a dependency, you need to associate a SqlDependency object to one or more SqlCommand objects. To receive notifications, you need to subscribe to the OnChange event. For more information about the requirements for creating queries for notifications, see "Creating a Query for Notification" in SQL Server Books Online

 

Thread.Begin(End)CriticalRegion: Notifies a host that execution is about to enter a region of code in which the effects of a thread abort or unhandled exception might jeopardize other tasks in the application domain.

 

Deploy the COM component by using ClickOnce http://msdn.microsoft.com/en-us/library/ms165432%28VS.80%29.aspx

Application.Settings http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx

Friday, September 25, 2009 9:44:08 PM UTC  #    Comments [0]    |  Trackback
 Thursday, September 24, 2009

Transaction Scope

Enumerate SQL Data sources.

CommandBehavior.SequentialAccess as a parameter for ExecuteReader method to support stream reading.

check Nested relation between two tables to make XML serialization results nested

PrintControllerWithStatusDialog

QueryPageSettings event

PrintDocument allows you to override the OnPrintPage method that can add a water mark on each page. The PrintController class will allow you to control the printing process but cannot force secure watermarks.

Basically, Assert gives some additional rights to untrusted code, while Demand requires that everyone in the call stack must have the required permissions.

CurrentUICulture only identifies the culture to be used by a resource manager.

The WorkerReportsProgress property should be set when ReportProgress is wanted to report the progress.

Event-based Asynchronous Pattern http://msdn.microsoft.com/en-us/library/wewwczdw.aspx
A class that supports the Event-based Asynchronous Pattern will have one or more methods named MethodNameAsync.
These methods may mirror synchronous versions, which perform the same operation on the current thread. The class
may also have a MethodNameCompleted event and it may have a MethodNameAsyncCancel (or simply CancelAsync) method.

The UserPaint flag shows that the control paints itself than having the operating system performs the job. If the flag is not set, the OnPaint method is not called.

ClickOnce Dynamic loading assembly: You should handle the AssemblyResolve event of the AppDomain class and call the DownLoadFileGroup method of the ApplicationDeployment class.

Mage.exe is used to change the GradeBook.application settings. It also helps to manage a published application.

x86 setting allows a package to be installed on 32-bit and 64-bit computer.

Thursday, September 24, 2009 9:11:15 PM UTC  #    Comments [0]    |  Trackback
 Monday, September 21, 2009

From the Amazon:

 

The authors have only added content for two new topics: 24 pages on LINQ and 3 pages on hosting a WPF control by using ElementHost. But they have missed out some important deployment-related topics that appear on the exam:
1) Install a Windows Presentation Foundation (WPF) browser application by using ClickOnce
2) Install a Visual Studio Tools for Office (VSTO) application by using ClickOnce
3) Configure and work with Windows Vista User Account Control (UAC) by using ClickOnce deployments
4) Set appropriate security permissions to deploy the application. This objective may include but is not limited to: elevated permissions
5) Configure Trusted Application deployments
6) Configure security features in an application. This objective may include but is not limited to: Configure code access security, configure the application to work with UAC, configure Windows manipulation permissions, configure appropriate file access permissions for the application, control printing security for the application

Monday, September 21, 2009 8:34:53 PM UTC  #    Comments [0]    |  Trackback

Accessibility
Flexibility;Choice of input and output method;Consistency;Compatibility with accessibility aids

PropertyGrid.SelectedObject = Button1;
PropertyGrid.PropertySort = PropertySort.Categorized; //Alphabetical, Categorized, CategorizedAlphabetical, NoSort

ToolStripProgressbar and ToolStripoStatusLabel
ToolTip.SetToolTip(Button1, “text”);

Set CauseValidation property; Add handler to Validating event; call ErrorProvider1.SetError(TextBox1, “”);
View Errors in a DataSet with the ErrorProvider Component.
errorProvider1.DataSource = DataSet1;
errorProvider1.DataMember = “Customers”;
errorProvider1.ContainerControl =  this;
DataTable.Rows[5].SetColumnError(“Name”, “The data is incorrect”);
this.BindingContext[DataTable1].Position = 5;

System.Media.SoundPlayer   play
System.Media.SystemSound.Beep.Play()

Bind a setting to a property at design time.  Application scope settings (read-only in run time) and user scope settings
Properties.Settings.Default.TitleSetting = “This is the new Title”;
Properties.Settings.Default.Save();

BAckGroundWorker.RunWorkAsync([parameter])
WorkerReportProgress = true; //set handler to ProgressChangedEvent, then call backgroundworker1.ReportProgress(…)

Asynchronous Method
Create a delegate, then you can call del.Invoke([Parameter]);
For asynchoronous call, we can call the methods BeginInvoke and EndInvoke P613
del = (myDelegate)result.AsyncState;
ResultString = del.EndInvoke(result);
SyncRoot of ArrayList
Control.InvokeRequired and ControlInvoke

Form1.TransparentKey = Color.Red
myUserControl.BackColor = Color.Red;

ToolboxBitmap Attribute

Custom Controls inherits from Control class. You can create the UI by implementating the OnPaint method.

Use ElementHost control to add WPF control to Windows Forms project
WPFProject.UserControl1 aWPFcontrol = new WPFProject.UserControl1;
ElementHost1.Child = aWPFcontrol;

Configureing REquired Permissions for a ClickOnce Application

Override the Install, Rollback, Uninstall, and Commit
InstallException cases the installation to be rolled back without leaving any lasting effect on the system

Monday, September 21, 2009 5:18:00 PM UTC  #    Comments [0]    |  Trackback

XML Document Object Model (DOM)
XMLDocument class exposes an XML Document as a hierachical collection of XmlNode objects.
XMLdocument.Load(parameter)// The parameter must be a String, Stream, TextWriter, or XmlWriter
XMLNode.Value XMLNode.InnerXml XMLNode.ReplaceChild XMLElement.SetAttribute(p1, p2)
XmlWriter awriter = Xml.XmlWriter.Create(“myFile.xml”);
aDocument.WriteTo(aWriter);  //equals to Write OuterXml
aDocument.WriteContentTo(aWriter); //equals to write innerXml
XmlDeclaration

PrintDocument Component
PrintPage Event
Tracking Page number and set HasMorePages property
PrintDocument.EndPrint event
PrintPermission class and PrintingPermissionLevel enumerations. //add to class as attribute
PrintPreviewControl

Drag-Drop
MouseEnter(call DoDragDrop) –> DragEnter(Set effect) –>DragDrop (get data)
AllowDrop property   e.Data.GetDataPresent   e.Data.GetData
TreeView:   ItemDrag –>DragEnter->DragDrop

Globalization refers to formatting existing data in formats appropriate for the current culture setting.
Localization, on the other hand, refers to retrieving appropriate data based on the culture.
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(“fr-CA”);
Set the UI culture in construction function of main form or in Application’s main function.
Localizable property and Language (only design time) property
RightToLeft proerty and RightToLeftLayout Property
Currentculture and CurrentUICulture

Set IsMDIContainer property to True in Parent Form
aChildForm.MdiParent = this
aForm = parentForm.ActiveMDIChild
LayoutMdi (enumerations)
List child form items in menu by set MdiWindowListItem property to the menu item

Monday, September 21, 2009 1:44:44 AM UTC  #    Comments [0]    |  Trackback
 Saturday, September 19, 2009

AutoIncrement, AutoIncrementSeed and AutoIncrementStep property

ForeignKeyConstrain class and UniqueConstrain class

Use CommandBuilder to automatically generate INSERT, UPDATE, and DELETE statements for the adapter
SqlDataAdapter adapter1 = new SqlDataAdapter(“Select *….);
SqlCommandBuilder commands = new SqlCommandBuilder(adapter1);

MissingMappingAction and MIssingSchemaAction Enumeration

Batch Updates with DataAdapter: Set UpdateBatchSize. 0 is the default that means largest batch size the server can process. When performing batch updates, the DataAdapter fires a RowUpdating event for each row being updated but fires only one RowUpdated event for the entire batch.

RowState enumberations: Unchanged, Added, Modified, Deleted, Detached
DataRow.RowError is assigned, the DataTable.HasErrors property is authmatically set to True.

Synchronizing a DataSet with an XmlDataDocument
XmlDataDocument NwDataDocument = new XmlDataDocument(NorthwindDataset);
Then pass an XPath query to the XMLDataDocument.DocumentElement.SelectNodes method. The SelectNodes method returns the data as a collection of Xml.Xmlnode (Xml.XmlNodeList)

DataView
DataView customerDataView = Northwind.Customers.DefaultView;
CustomerDataView.Sort = “ContactName DESC”;
int FoundRow = CustomersDataView.Find(“FADF”); //FoundRow is index
OrderDataView = CustomersDataRowView.CreateChildView(“FK_Orders_Customers”);  //RataRelation

ListChanged event of DataView

Using DataViewManager as the databind source to manage several tables.
DataViewManager dvm = new DataViewManager(NorthwindDataSet1);
OrderDataGridView.DataSource = dvm.DataViewSettings(“Customers”).Table

BindingSource
customersBindingSource = new BindingSource(northwindDataSet1, “Customers”);

Validating input in DataGridView by handling the DataGridView.CellValidating event

handle the CellPainting event to customize the DataGridView

XmlTextReader, XmlNodeReader both are implementations of the XmlReader class


XmlValidatingReader aValReader = new XmlValidatingReader(aReader);
DTD document type definition
XSD extensible schema definition
SDR XML-Data Reduced (XDR) schema
ValidationEvent

XmlReaderSettings.ValidationType  and ValidationEventHandler
XmlWriter.Create(parameter, [XmlWriterSettings])//parameter can be a stream, a file, stringBuilder, TextWriter, or XmlWriter

Saturday, September 19, 2009 11:40:27 PM UTC  #    Comments [0]    |  Trackback
 Friday, September 18, 2009

FlowLayoutPanel    Method: SetFlowBreak(Control, bool) and GetFlowBreak

Document Outline Window

TextBox Property Lines is a string array representing the individual lines of the text box.

MaskedTextBox

ListBox.Sorted = true

ListView

DomainUpDown

UseMnemonic Property

ToolStrip ToolStripItem ToolStripContainer ToolStripManager.Merge

Connection Events: StateChanged and InfoMessage

SqlException  SqlDataSourceEnumberator.Instance.GetDataSource()

Persist Security Information should be false in the connection string to ensure that the credentials used to open the connection are discarded and not stored where someone might be able to retrieve them.

Use protected-configuration provider to encrypt configuration data.

ConfigurationSection connstrings = config.ConnectionStrings;
connstrings.SectionInformation.ProtectSection(provider);
connstrings.sectionInformation.ForceSave = true;
config.Save(configurationSaveMode.Full);

SqlCommand.ExecuteXMLReader(); //SqlCommand only

Asynchoronous SQL Command

Call nextResult to get result from multiple SQL Statement execution

Byte[] BLOB;
BLOB = fileReader.ReadBytes((int)(file.Length));

SqlBulkCopy   (with optional Transaction)
SqlBulkCopy BulkCopier = new SqlBulkCopy(DestinationConnection, UserInternalTransaction);
BuilkCopier.DestinationTableName=”XXX”;
BulkCopier.WriteToServer(reader);

(Bulk Insert Statement only for SQL) data from .bcp file
string BulkInsertStatement = “BULK INSERT CustomerHIstory FROM ‘c:\\NorthwindCustomers.txt’”;

Isolation Level of a Transaction

Enlist Transaction to a distrubuted transaction
NorthWindConnection.EnlistTRansaction(activeTransaction);

LINQ queries against any .Net Framework collection that implements IEnumberable, IEnumerable<T> or inherited from IEnumerable<T>

DataRow.GetParentRow(string foreignkey)       DataRow.GetChildRows(string foreignkey)

DataSet.Merge(sourcedataset, IfPreserveChanges, MIssingSchemaAction)
DataSet.Copy()

Friday, September 18, 2009 6:54:08 PM UTC  #    Comments [0]    |  Trackback
 Thursday, September 17, 2009

.Net targeting http://msdn.microsoft.com/en-us/library/9w519wzk.aspx

BitVector32 constructor takes takes an Int32 parameter.

Going back to Microprocessor basics, all modern processors stores negative number in 2's complement notation.

0 is stored as "0...(32 zeroes)" in binary

1 is stored as "00000.....1" as a 32 bit binary

-1 is stored as "1111 ...1" as a 32 bit binary

Search on 2's complement and read on for further clarity.

 

ArrayList.Synchronized method

 

IDeserializationCallback and OnDeserialization Method
Process.GetProcessesByName (String, processName, String computerName) 
Process.GetProcesses() GetProcessesById(Int32, [string]), there is no GetProcesses(string name) 
CLR (Unit of isolation) is AppDomain
DEVPATH http://msdn.microsoft.com/en-us/library/cskzh7h6%28VS.71%29.aspx
[XMLArrayItem(Type = typeof(yourclass))] http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlarrayitemattribute.aspx
Evidence evidence = new Evidence();
evidence.AddHost(new Zone(SecurityZone.Intranet));
CompareInfo:Implements a set of methods for culture-sensitive string comparisons.  http://msdn.microsoft.com/en-us/library/system.globalization.compareinfo.aspx
Assembly.LoadFrom(Path) Assembly.Load(AssemblyName)
HashAlgorithm instance.ComputeHash()
Exposing .net class to Com needs non-parameter constructor in .Net class?
Change security settings of a file ObjectSecurity.SetAccessRuleProtection(isProtected, preserveInheritance)
ServiceController.MachineName property (You can use the ServiceController class to connect to and control the behavior of existing services. 
When you create an instance of the ServiceController class, you set its properties so it interacts with a specific Windows service. You can then use the class to start, stop, 
and otherwise manipulate the service.)
BufferedStream
 
ManagementObjectSearcher: syntax is like PL-SQL
Thursday, September 17, 2009 5:45:10 PM UTC  #    Comments [0]    |  Trackback
 Monday, September 07, 2009

SharePoint

Business Intelligence Design Studio (BIDS) 2008

Report Builder 2.0

jacobs@resolute.com  spsguru@gmail.com

http://community.bamboosolutions.com/default.aspx

Middleware

www.linxter.com

http://www.thinqlinq.com/

Monday, September 07, 2009 4:05:10 PM UTC  #    Comments [0]    |  Trackback
 Monday, August 17, 2009

http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/74dac8d1-6fa7-4d23-a740-738f9c707d28

This exception says that you are deleting a relationship but not the entity association with that relationship.  Sometimes that's OK, but if your relationship is a 1-to-many (rather than 0..1-to-many) that means the entities on the many side cannot exist independent of the entity on the one side.  In your case, you are deleting the relationship between a Link and a WebPage, but the Link cannot exist on its own independent of the WebPage.
Configuring a cascade delete doesn't make it so that deleting the relationship will delete the entity--what it does is make it so that deleting the entity on one side of a relationship will cause the entity on the other side to be deleted.  So that doesn't fix the issue in this case.
The fix in this case would be to change the line at the end of FromBusinessObject from
    this.Links.Remove(entity);
to
    context.DeleteObject(entity);
Of course that also means you will need to pass the context to the FromBusinessObject method or something like that...
This change will cause the link entity to be deleted which implicitly deletes any relationships it participates in rather than just deleting the relationship between the page and the link.

 

   1:          partial void OnContextCreated()
   2:          {
   3:              this.SavingChanges += new EventHandler(onSavingChanges);
   4:          }
   5:   
   6:          private static void onSavingChanges(object sender, EventArgs e)
   7:          {
   8:              foreach (ObjectStateEntry entry in ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
   9:              {
  10:                  if (entry.IsRelationship)
  11:                  {
  12:                      AssociationType asso = (AssociationType)entry.EntitySet.ElementType;
  13:   
  14:                      if (asso.RelationshipEndMembers[0].RelationshipMultiplicity == RelationshipMultiplicity.One && asso.RelationshipEndMembers[1].RelationshipMultiplicity == RelationshipMultiplicity.Many)
  15:                      {
  16:                          object o = entry.OriginalValues[1];
  17:                          object ob = ((ObjectContext)sender).GetObjectByKey((EntityKey)o);
  18:                          ((ObjectContext)sender).DeleteObject(ob);
  19:                      }
  20:                      else if (asso.RelationshipEndMembers[1].RelationshipMultiplicity == RelationshipMultiplicity.One && asso.RelationshipEndMembers[0].RelationshipMultiplicity == RelationshipMultiplicity.Many)
  21:                      {
  22:                          object o = entry.OriginalValues[0];
  23:                          object ob = ((ObjectContext)sender).GetObjectByKey((EntityKey)o);
  24:                          ((ObjectContext)sender).DeleteObject(ob);
  25:                      }
  26:                  }
  27:              }
  28:          }
Monday, August 17, 2009 9:19:41 PM UTC  #    Comments [0]    |   |  Trackback
 Tuesday, August 11, 2009
 Monday, July 20, 2009
 Monday, June 22, 2009

http://support.microsoft.com/kb/257757

Alternatives to server-side Automation

The Open XML file formats are a public standard. To obtain a copy of the specification, visit the following Web site:

http://www.ecma-international.org/publications/standards/Ecma-376.htm (http://www.ecma-international.org/publications/standards/Ecma-376.htm)

Microsoft provides an SDK for manipulating Open XML file formats from the .NET 3.x Framework. For more information about the SDK and about how to use the SDK to create or edit Open XML files, visit the following Microsoft Developer Network (MSDN) Web sites:

Open XML SDK Documentation
http://msdn.microsoft.com/en-us/library/bb226703.aspx (http://msdn.microsoft.com/en-us/library/bb226703.aspx)

How to: Manipulate Office Open XML Formats Documents
http://msdn.microsoft.com/en-us/library/aa982683.aspx (http://msdn.microsoft.com/en-us/library/aa982683.aspx)

Manipulating Word 2007 Files with the Open XML Object Model (Part 1 of 3)
http://msdn.microsoft.com/en-us/library/bb656295.aspx (http://msdn.microsoft.com/en-us/library/bb656295.aspx)

Manipulating Word 2007 Files with the Open XML Object Model (Part 2 of 3)
http://msdn.microsoft.com/en-us/library/bb739835.aspx (http://msdn.microsoft.com/en-us/library/bb739835.aspx)

Manipulating Word 2007 Files with the Open XML Object Model (Part 3 of 3)
http://msdn.microsoft.com/en-us/library/bb727374.aspx (http://msdn.microsoft.com/en-us/library/bb727374.aspx)

Manipulating Excel 2007 and PowerPoint 2007 Files with the Open XML Object Model (Part 1 of 2)
http://msdn.microsoft.com/en-us/library/bb739834.aspx (http://msdn.microsoft.com/en-us/library/bb739834.aspx)

Manipulating Excel 2007 and PowerPoint 2007 Files with the Open XML Object Model (Part 2 of 2)
http://msdn.microsoft.com/en-us/library/bb727373.aspx (http://msdn.microsoft.com/en-us/library/bb727373.aspx)

Building Server-Side Document Generation Solutions Using the Open XML Object Model (Part 1 of 2)
http://msdn2.microsoft.com/en-us/library/bb735940.aspx (http://msdn2.microsoft.com/en-us/library/bb735940.aspx)

Building Server-Side Document Generation Solutions Using the Open XML Object Model (Part 2 of 2)
http://msdn2.microsoft.com/en-us/library/bb735939.aspx (http://msdn2.microsoft.com/en-us/library/bb735939.aspx)

For more information about using Open XML from the .NET 3.0 Framework and for an example, click the following article numbers to view the articles in the Microsoft Knowledge Base:

932921 (http://support.microsoft.com/kb/932921/ ) How to use components of the .NET Framework 3.0 to create and then to stream an Office Word 2007 document and an Office Excel 2007 workbook to a client computer

931866 (http://support.microsoft.com/kb/931866/ ) How to use the Office XML file format and the packaging components from the .NET Framework 3.0 to create a simple Excel 2007 workbook or a simple Word 2007 document

Users who are running earlier versions of Office (such as Office 2000, Office XP, and Office 2003) can view and edit Open XML files if the users install the free compatibility pack download from the Microsoft Web site. To download and install the compatibility pack, visit the following Microsoft Web site:

Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 file formats
http://office.microsoft.com/en-us/products/HA101686761033.aspx (http://office.microsoft.com/en-us/products/HA101686761033.aspx)

When you stream Open XML files from ASP or from ASP.NET, you must provide the correct Multipurpose Internet Mail Extension (MIME) type for the content that you stream. For a listing of the MIME types for Office 2007 files, visit the following Web site:

http://blogs.msdn.com/vsofficedeveloper/pages/Office-2007-Open-XML-MIME-Types.aspx (http://blogs.msdn.com/vsofficedeveloper/pages/Office-2007-Open-XML-MIME-Types.aspx)

 

 

 

Documentation:

· Open XML Markup Language Reference (ECMA specification)

http://www.ecma-international.org/publications/files/ECMA-ST/Office%20Open%20XML%201st%20edition%20Part%204%20(PDF).zip

· ECMA-376 Implementer notes for Office 2007 SP2 (will help ECMA-376 implementers interoperate with Office by explaining, among other things, Office’s support for optional features, range restrictions for attribute values, and how Office’s functionality maps to Open XML constructs. 

http://www.documentinteropinitiative.org/implnotes/ecma-376/ec354bc5-2931-46ca-b117-cc8ba7e5a33c.aspx

· MSDN Library (including introduction of Open XML SDK and How-To articles)

http://msdn.microsoft.com/en-us/library/bb448854(office.14).aspx

MSDN Open XML File Format Center

http://msdn.microsoft.com/en-us/office/bb265236.aspx

Forums:

· Connect Site (including A=articles, downloadable sample code, customer feedbacks, surveys, etc. Need to firstly register as a member, then choose the “Open Xml SDK” group to join in)

https://connect.microsoft.com/site/sitehome.aspx?SiteID=589

· MSDN forum (a forum for worldwide customers to submit  any questions , feedbacks and requirements)

http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/threads/

· Open XML Developer forum (a forum for worldwide customers to submit  any questions , feedbacks and requirements)

http://openxmldeveloper.org/forums/default.aspx

Tutorial Book:

· e-book: Open Xml Explained (very detail introduction of Open Xml Format SDK concepts and markup explanation)

http://openxmldeveloper.org/articles/1970.aspx

Blog Posts:

· Brian Jone’s Blog (very useful articles about Open Xml  Format SDK basic concepts and sample code of real-world solutions)

http://blogs.msdn.com/brian_jones/

· Eric White’s Blog (very useful articles about file format, Open Xml SDK related technologies and useful tools)

http://blogs.msdn.com/ericwhite/default.aspx

· Erika Ehrli’s Blog

http://blogs.msdn.com/erikaehrli/default.aspx

· Doug Mahuge

http://blogs.msdn.com/dmahugh/

Monday, June 22, 2009 6:09:29 PM UTC  #    Comments [0]    |  Trackback
 Wednesday, June 10, 2009

http://msdn.microsoft.com/en-us/library/aa720433(VS.71).aspx

Programming with the .NET Framework

This section describes the programming essentials you need to build .NET applications, from creating assemblies from your code to securing your application. Many of the fundamentals covered in this section are used to create any application using the .NET Framework. This section provides conceptual information about key programming concepts, as well as code samples and detailed explanations.

In This Section
Accessing Data with ADO.NET
Describes the ADO.NET architecture and how to use the ADO.NET classes to manage application data and interact with data sources, including Microsoft SQL Server, OLE DB data sources, and XML.
Accessing Objects in Other Application Domains Using .NET Remoting
Describes the various communications methods available in the .NET Framework for remote communications.
Accessing the Internet
Shows how to use Internet access classes to implement both Web- and Internet-based applications.
Creating Active Directory Components
Discusses using Active Directory Services Interfaces (ADSI).
Creating Messaging Components
Discusses how to build complex messaging into your applications.
Creating System Monitoring Components
Discusses how to use performance counters and event logs with your application.
Creating Timer-Based Server Tasks
Discusses how to create events that are raised on reoccurring intervals.
Developing Components
Provides an overview of component programming and explains how those concepts work with the .NET Framework.
Developing World-Ready Applications
Explains the extensive support the .NET Framework provides for developing international applications.
Discovering Type Information at Run Time
Explains how to get access to type information at run time by using reflection.
Drawing and Editing Images
Discusses using GDI+ with the .NET Framework.
Emitting Dynamic Assemblies
Describes the set of managed types in the System.Reflection.Emit namespace.
Employing XML in the .NET Framework
Provides an overview to a comprehensive and integrated set of classes that work with XML documents and data in the .NET Framework.
Extending Metadata Using Attributes
Describes how you can use attributes to customize metadata.
Generating and Compiling Source Code Dynamically in Multiple Languages
Explains the .NET Framework SDK mechanism called the Code Document Object Model (CodeDOM), which enables the output of source code in multiple programming languages.
Grouping Data in Collections
Discusses the various collection types available in the .NET Framework, including stacks, queues, lists, arrays, and structs.
Handling and Raising Events
Provides an overview of the event model in the .NET Framework.
Handling and Throwing Exceptions
Describes error handling provided by the .NET Framework and the fundamentals of handling exceptions.
Hosting the Common Language Runtime
Explains the concept of a runtime host, which loads the runtime into a process, creates the application domain within the process, and loads and executes user code.
Including Asynchronous Calls
Discusses asynchronous programming features in the .NET Framework.
Interoperating with Unmanaged Code
Describes interoperability services provided by the common language runtime.
Managing Applications Using WMI
Explains how to create applications using Windows Management Instrumentation (WMI), which provides a rich set of system management services built into the Microsoft® Windows® operating systems.
Processing Transactions
Discusses the .NET Framework support for transactions.
Programming for Garbage Collection
Discusses how the garbage collector manages memory and how you can program to use memory more efficiently.
Programming with Application Domains and Assemblies
Describes how to create and work with assemblies and application domains.
Securing Applications
Describes .NET Framework code access security, role-based security, security policy, and security tools.
Serializing Objects
Discusses XML serialization.
Threading
Explains the runtime support for threading and how to program using various synchronization techniques.
Using Side-by-Side Execution
Explains what side-by-side execution is and how you can use it to run multiple copies of an application, a component, or the entire runtime.
Working With Base Types
Discusses formatting and parsing base data types and using regular expressions to process text.
Working with I/O
Explains how you can perform synchronous and asynchronous file and data stream access, and how to use to isolated storage.
Writing Serviced Components
Describes how to configure and register serviced components to access COM+ services.
Related Topics
Creating ASP.NET Web Applications
Discusses how to create and optimize ASP.NET Web applications.
Creating Windows Forms Applications
Describes how to create Windows Forms and Windows controls applications.
Building Console Applications
Discusses how to create console-based .NET applications.
Wednesday, June 10, 2009 8:20:16 PM UTC  #    Comments [0]    |  Trackback

 

Sachabarber’s extension method http://sachabarber.net/?p=411 (Five start solution)

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/82c6451d-d37b-4380-aa11-d75c2f759ba7/

XAML:
<Window x:Class="WindowsApplication1.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Testing BackgroundWorker" Height="300" Width="300" 
    > 
    <Grid> 
        <Button HorizontalAlignment="Left" Margin="8,25,0,0" x:Name="_btnStart" VerticalAlignment="Top" Width="87" Height="27" Content="Start" Click="StartWorker"/> 
        <Button IsEnabled="False" Margin="99,25,102,0" x:Name="_btnCancel" VerticalAlignment="Top" Height="27" Content="Cancel" Click="CancelWorker"/> 
        <ProgressBar Margin="8,0,8,107" x:Name="_progressBar" VerticalAlignment="Bottom" Height="23" Maximum="10"/> 
    </Grid> 
</Window> 
C#:
using System.ComponentModel; 
using System.Threading; 
using System.Windows; 
namespace WindowsApplication1 
{ 
    /// <summary> 
    /// Interaction logic for Window1.xaml 
    /// </summary> 
    public partial class Window1 : System.Windows.Window 
    { 
        private BackgroundWorker _worker; 
        public Window1() 
        { 
            InitializeComponent(); 
        } 
        private void StartWorker(object sender, RoutedEventArgs e) 
        { 
            int N = 10; 
            _worker = new BackgroundWorker(); 
            _worker.WorkerReportsProgress = true; 
            _worker.WorkerSupportsCancellation = true; 
            _worker.DoWork += delegate(object s, DoWorkEventArgs args) 
                { 
                    BackgroundWorker worker = s as BackgroundWorker; 
                    for (int i = 0; i < N; i++) 
                    { 
                        if (worker.CancellationPending) 
                        { 
                            args.Cancel = true; 
                            return; 
                        } 
                        Thread.Sleep(1000); 
                        worker.ReportProgress(i + 1); 
                    } 
                }; 
            _worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args) 
                { 
                    _progressBar.Value = args.ProgressPercentage; 
                }; 
            _worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args) 
                { 
                    _btnStart.IsEnabled = true; 
                    _btnCancel.IsEnabled = false; 
                    _progressBar.Value = 0; 
                }; 
            _worker.RunWorkerAsync(); 
            _btnStart.IsEnabled = false; 
            _btnCancel.IsEnabled = true; 
        } 
        private void CancelWorker(object sender, RoutedEventArgs e) 
        { 
            _worker.CancelAsync(); 
        } 
    } 
} 
Wednesday, June 10, 2009 6:00:32 PM UTC  #    Comments [0]    |   |  Trackback
 Friday, June 05, 2009
 Thursday, June 04, 2009
 Wednesday, June 03, 2009
 Tuesday, June 02, 2009
Tuesday, June 02, 2009 6:05:49 PM UTC  #    Comments [0]    |   |  Trackback
 Thursday, May 28, 2009

http://blog.schuager.com/2009/01/line-count-in-visual-studio.html

Select Edit -> Find & Replace -> Find in files... or just press CTRL+SHIFT+F
Check Use and select Regular expressions.
Type the following as the text to find:

^~(:Wh@//.+)~(:Wh@\{:Wh@)~(:Wh@\}:Wh@)~(:Wh@/#).+
Select where you want to do the search/count: file, project or solution.
Thursday, May 28, 2009 2:14:18 AM UTC  #    Comments [0]    |  Trackback
 Monday, April 20, 2009

From http://www.codethinked.com/

 

Simone Chiaretta’s CodeClimber - A good friend, and a better blogger. Simone is an ASP.NET MVP and is co-writing the book “Beginning ASP.NET MVC 1.0” by Wrox. Simone blogs about all sorts of different ASP.NET MVC topics, and will certainly bring tons more content once he finishes his book. He is also an active developer on the Subtext project.

 

Stephen Walther - Stephen is a Senior Program Manager at Microsoft where he creates much of the tutorial content on the www.asp.net/mvc website. Somehow he also finds time to put up tons of helpful posts on his personal blog. He is also authoring the book “ASP.NET MVC Framework Unleashed” by Sams.

 

Kazi Manzur Rashid - Kazi is surprisingly the only person on this list who isn’t writing a book! He is also an ASP.NET MVP and his claim to fame is dotnetshoutout.com (which is a great site) and the open source Kigg project. He writes tons of posts on ASP.NET MVC, and has recently been on quite a run with many lengthy and in-depth articles.

 

Maarten Balliauw - Maarten is authoring the book ASP.NET MVC 1.0 Quickly by Packt. I’m not sure how Maarten has time to write the book and his blog, because he has been pumping out quite a few awesome ASP.NET MVC posts recently.

 

Steve Sanderson - Steve is the author of Pro ASP.NET MVC Framework by Apress and like these other guys, still finds time to write some good informative posts on his blog. He is also the author of the xVal validation framework which aims to help developers more easily tie domain validations to the front-end web application.

 

Luis Abreau – This one is a bonus, and was added because of Marwan's comment below. I went and checked it out, and there are many great little ASP.NET MVC tidbits on this guys blog. Too bad there isn't much information about him at all. It looks like he might be a current or former MVP, I don't know. He has a linked in profile, but not too much info there other than the fact that he is in Portugal. So lots of good ASP.NET MVC information, but other than that, I don't know what to tell you about the guy!

Monday, April 20, 2009 4:16:55 PM UTC  #    Comments [0]    |   |  Trackback

Comparison

“Glenn sums up the differences well by saying that MEF is about extensibility whilst MAF is about isolation. Moreover, they are not mutually exclusive. It is entirely possible - and legitimate - to use both together.”

http://kentb.blogspot.com/2009/02/maf-and-mef.html

MEF

MEF is all about extensibility.

(Brad Abrams) Simple Introduction to Extensible Applications with the Managed Extensions Framework http://blogs.msdn.com/brada/archive/2008/09/29/simple-introduction-to-composite-applications-with-the-managed-extensions-framework.aspx

Addicted To MEF (part1, part2)

How to create plug-in module by using MEF http://www.milkcarton.com/blog/2009/04/04/5+Minute+Tutorial+On+Managed+Extensibility+Framework+MEF.aspx

 

MAF

Add-in Overview http://msdn.microsoft.com/en-us/library/bb384200.aspx

Managed AddIn Framework (System.AddIn) with WPF http://www.matthidinger.com/archive/2008/10/12/managed-addin-framework-system.addin-with-wpf.aspx

MAF Video http://channel9.msdn.com/posts/DanielMoth/Managed-AddIn-Framework/

Monday, April 20, 2009 2:47:33 PM UTC  #    Comments [0]    |  Trackback
 Friday, March 13, 2009
 Monday, February 16, 2009
 Friday, January 16, 2009
Friday, January 16, 2009 2:56:22 PM UTC  #    Comments [0]    |   |  Trackback
 Friday, January 09, 2009

http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx

  1. In Visual Studio, click Tools -> External Tools...
  2. Click Add and enter the following into the different fields as displayed in the following screenshot:
    • Title: Get Public Key
    • Command: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe
    • Arguments: -Tp "$(TargetPath)"
    • Uncheck all options, except Use Output window\
Friday, January 09, 2009 4:29:10 PM UTC  #    Comments [0]    |  Trackback
@for %%e in (%PATHEXT%) do @for %%i in (%1%%e) do @if NOT "%%~$PATH:i"=="" echo %%~$PATH:i
Friday, January 09, 2009 4:26:31 PM UTC  #    Comments [0]    |  Trackback
 Friday, December 12, 2008

How to Debug: http://weblogs.asp.net/joshrobinson/archive/2004/12/20/327381.aspx

System.Diagnostics.Debugger.Break();

Walk Through http://msdn.microsoft.com/en-us/library/d9k65z2d(VS.80).aspx

Add custom action to both install and commit

How to get installation path

string strAssemplyPath = Context.Parameters["assemblypath"].ToString();

string strAppPath = strAssemplyPath.Substring(0, strAssemplyPath.LastIndexOf("\\"));

Friday, December 12, 2008 9:46:27 PM UTC  #    Comments [0]    |   |  Trackback
 Wednesday, November 26, 2008

Build and Deploy .Net COM Assembly

http://www.simple-talk.com/dotnet/visual-studio/build-and-deploy-a-.net-com-assembly/

Differences of regasm.exe and regsvr32.exe

http://forums.asp.net/t/1019678.aspx

http://blogs.msdn.com/csharpfaq/archive/2004/08/02/206158.aspx

"regasm.exe is used to create COM Callable Wrapper (CCW) around .NET assemblies. .NET managed assemblies(EXEs, DLLs) are different from COM DLLs (which are unmanaged, ie. they interact with the OS directly). So to register an unmanaged DLL you use regsvr32.exe.

But if you have a managed .NET assembly and want you COM components to use it as if it were a COM assembly, then you need to use regasm.exe."

Get started with .Net Setup Project

http://www.simple-talk.com/dotnet/visual-studio/getting-started-with-setup-projects/

Wednesday, November 26, 2008 3:40:18 PM UTC  #    Comments [0]    |   |  Trackback
 Tuesday, November 11, 2008

http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci1255498,00.html

         public static void GenerateRsa(string privateKeyPath, string publicKeyPath, int size)
        {
            //stream to save the keys
            FileStream fs = null;
            StreamWriter sw = null;

            //create RSA provider
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(size);
            try
            {
                //save private key
                fs = new FileStream(privateKeyPath, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs);
                sw.Write(rsa.ToXmlString(true));
                sw.Flush();
            }
            finally
            {
                if (sw != null) sw.Close();
                if (fs != null) fs.Close();
            }

            try
            {
                //save public key
                fs = new FileStream(publicKeyPath, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs);
                sw.Write(rsa.ToXmlString(false));
                sw.Flush();
            }
            finally
            {
                if (sw != null) sw.Close();
                if (fs != null) fs.Close();
            }
            rsa.Clear();
        }
Tuesday, November 11, 2008 6:00:16 PM UTC  #    Comments [1]    |  Trackback
 Friday, October 17, 2008
ProcessStartInfo si = new ProcessStartInfo("cmd.exe");
// Redirect both streams so we can write/read them.
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
si.UseShellExecute = false;
// Start the procses.
Process p = Process.Start(si);
// Issue the dir command.
p.StandardInput.WriteLine(@"dir c:");
// Exit the application.
p.StandardInput.WriteLine(@"exit");
// Read all the output generated from it.
string output = p.StandardOutput.ReadToEnd();
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/ShellCommandsInCS12032005042031AM/ShellCommandsInCS.aspx
Friday, October 17, 2008 5:55:22 PM UTC  #    Comments [0]    |  Trackback
 Thursday, October 16, 2008

http://www.dotnetinterop.com/faq/?q=LoadLibrary

You can load the DLL manually before the CLR tries to do it for you, using the LoadLibrary Win32 API. By passing it the fully qualified path, you can bypass the regular search path rules.

The following code calls the exported function MyFunc in unmanaged.dll, located in the ..\unmanaged directory relative to the executable.

C#

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
static extern IntPtr LoadLibrary(string lpFileName);

[DllImport("unmanaged.dll")]
static extern int MyFunc(int i);

static void Main()
{
  // Ensure current directory is exe directory
  Environment.CurrentDirectory = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );

  string dllPath = Path.GetFullPath( @"..\unmanaged\unmanaged.dll" );
  LoadLibrary( dllPath );
  Console.WriteLine( MyFunc( 5 ) );
} 
 

VB.NET

Declare Auto Function LoadLibrary Lib "kernel32.dll" (ByVal lpFileName As String) As IntPtr

Declare Function MyFunc Lib "unmanaged.dll" (ByVal i As Integer) As Integer

Shared Sub Main()
  ' Ensure current directory is exe directory
  Environment.CurrentDirectory = Path.GetDirectoryName([Assembly].GetExecutingAssembly().Location)

  Dim dllPath As String = Path.GetFullPath("..\unmanaged\unmanaged.dll")
  LoadLibrary(dllPath)
  Console.WriteLine(MyFunc(5))
End Sub
    
Thursday, October 16, 2008 5:49:35 PM UTC  #    Comments [0]    |  Trackback
 Friday, October 10, 2008

1. Select the directory.

2. In the top buttons, choose "Show all files"

3. Select the directory again and choose "include in project"

4. you can choose "refresh" button on the top to update the content in the directory, and then add those new added items again.

Friday, October 10, 2008 6:30:05 PM UTC  #    Comments [0]    |  Trackback
 Tuesday, September 16, 2008
 Thursday, September 11, 2008
http://dn.codegear.com/article/32384
Environment.SpecialFolder.ApplicationData
Environment.SpecialFolder.System
Environment.SpecialFolder.CommonApplicationData
Environment.SpecialFolder.CommonProgramFiles
Environment.SpecialFolder.Cookies
Environment.SpecialFolder.Desktop
Environment.SpecialFolder.DesktopDirectory
Environment.SpecialFolder.Favorites
Environment.SpecialFolder.History
Environment.SpecialFolder.InternetCache
Environment.SpecialFolder.LocalApplicationData
Environment.SpecialFolder.MyComputer
Environment.SpecialFolder.MyMusic
Environment.SpecialFolder.MyPictures
Environment.SpecialFolder.Personal (My documents)
Environment.SpecialFolder.ProgramFiles
Environment.SpecialFolder.Programs
Environment.SpecialFolder.Recent
Environment.SpecialFolder.SendTo
Environment.SpecialFolder.StartMenu
Use Environment.GetFolderPath() function to get the physical path string
Thursday, September 11, 2008 6:21:18 PM UTC  #    Comments [0]    |  Trackback
 Monday, September 08, 2008

http://www.cnblogs.com/reallypride/archive/2008/09/08/1287095.html

Enum

namespace EnumTest
{
    enum date { sun, mon, tue, wes, thu, fri, sat }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("输入星期的名称:");
            string name = Console.ReadLine();

            //Type参数表示要转换成的枚举的类型,true指示忽略大小写
            object obj = Enum.Parse(typeof(date), name, true);
            Console.WriteLine("输出星期的数字:");
            Console.WriteLine(obj + ":" + (int)obj);
        }
    }
}

Delegate

namespace DelegateTest
{
    class Person
    {
        public void FirstMethod()
        {
            Console.WriteLine("这是第一个方法!");
        }
        public void SecondMethod()
        {
            Console.WriteLine("这是第二个方法!");
        }
    }
    
    delegate void dele();

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("输入方法的名字:");
            string name = Console.ReadLine();
            Person p = new Person();

            //Type参数是要转换的委托的类型,p是要调用的委托的实例,true指示忽略大小写
            dele d = Delegate.CreateDelegate(typeof(dele), p, name + "Method", true) as dele;
            d.Invoke();
            Console.WriteLine("输入方法的名字:");
            name = Console.ReadLine();
            d = Delegate.CreateDelegate(typeof(dele), p, name + "method", true) as dele;
            d.Invoke();
        }
    }
}

Anonymous Method

namespace Anonymity
{
    delegate void dele();
    class Program
    {
        static void Main(string[] args)
        {
            dele d = delegate() { Console.WriteLine("这是一个匿名方法!"); };
            d.Invoke();
        }
    }
}

Indexer

namespace IndexerTest
{
    class PersonNames
    {
        List<string> names = new List<string>();
        /// <summary>
        /// 为对象创建索引器,注意它和属性的get/set的不同
        /// </summary>
        /// <param name="index">索引值</param>
        /// <returns></returns>
        public string this[int index]
        {
            get { return names[index]; }
            set { names.Add(value); }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            PersonNames names = new PersonNames();
            names[0] = "微软";
            names[1] = "谷歌";
            names[2] = "百度";
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(names[i]);
            }
        }
    }
}

HashTable

namespace HashTableTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable table = new Hashtable();
            table["name1"] = "微软";
            table.Add("name2", "谷歌");
            table["name3"] = "百度";
            //注意name的类型名
            foreach (DictionaryEntry name in table)
            {
                Console.WriteLine(name.Key + ":" + name.Value);
            }
        }
    }
}
Monday, September 08, 2008 10:36:40 PM UTC  #    Comments [0]    |  Trackback
 Thursday, September 04, 2008
Thursday, September 04, 2008 2:44:47 PM UTC  #    Comments [0]    |  Trackback
 Tuesday, September 02, 2008
// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
   public static void Main() 
   {

      #if (DEBUG && !VC_V7)
         Console.WriteLine("DEBUG is defined");
      #elif (!DEBUG && VC_V7)
         Console.WriteLine("VC_V7 is defined");
      #elif (DEBUG && VC_V7)
         Console.WriteLine("DEBUG and VC_V7 are defined");
      #else
         Console.WriteLine("DEBUG and VC_V7 are not defined");
      #endif
   }
}

http://msdn.microsoft.com/en-us/library/4y6tbswk(VS.71).aspx

Tuesday, September 02, 2008 8:23:45 PM UTC  #    Comments [0]    |  Trackback
 Thursday, August 21, 2008
 Tuesday, August 12, 2008

http://www.c-sharpcorner.com/UploadFile/nagryum/Appdomain07102007081415AM/Appdomain.aspx

Advantages

A single CLR operating system process can contain multiple application domains. There are advantages to having application domains within a single process.

  1. Lower system cost - many application domains can be contained within a single system process.

  2. Each application domain can have different security access levels assigned to them, all within a single process.

  3. Code in one AppDomain cannot directly access code in another AppDomain.

  4. The application in an AppDomain can be stopped without affecting the state of another AppDomain running in the same process.

  5. An  Exception in on AppDomain will not affect other AppDomains or crash the entire process that hosts the AppDomains.

Tuesday, August 12, 2008 2:27:11 PM UTC  #    Comments [0]    |  Trackback
 Monday, April 21, 2008
 Monday, March 03, 2008

http://weblogs.asp.net/scottgu/archive/2007/11/19/visual-studio-2008-and-net-3-5-released.aspx

 

Quick Tour of Some of the New Features

Visual Studio 2008 and .NET 3.5 contain a ton of new functionality and improvements.  Below are links to blog posts I've done myself as well as links to videos you can watch to learn more about it:

VS 2008 Multi-Targeting Support

VS 2008 enables you to build applications that target multiple versions of the .NET Framework.  This means you can use VS 2008 to open, edit and build existing .NET 2.0 and ASP.NET 2.0 applications (including ASP.NET 2.0 applications using ASP.NET AJAX 1.0), and continue to deploy these application on .NET 2.0 machines.  You can learn more about how this works from my blog post here:

ASP.NET AJAX and JavaScript Support

.NET 3.5 has ASP.NET AJAX built-in (no separate download required).  In addition to including all of the features in ASP.NET AJAX 1.0, ASP.NET 3.5 also now includes richer support for UpdatePanels integrating with WebParts, ASP.NET AJAX integration with controls like <asp:menu> and <asp:treeview>, WCF support for JSON, and many other AJAX improvements.

VS 2008 and Visual Web Developer 2008 also now have great support for integrating JavaScript and AJAX into your applications.  You can learn more about this from my blog posts here:

You can watch some videos that discuss ASP.NET AJAX and Visual Studio 2008 support for it here

I also highly recommend the excellent ASP.NET AJAX in Action book to learn more about ASP.NET AJAX (both client-side and server-side).

VS 2008 Web Designer and CSS Support

VS 2008 and Visual Web Developer 2008 Express includes a significantly improved HTML web designer (the same one that ships with Expression Web).  This delivers support for split-view editing, nested master pages, and great CSS integration.  Below are some articles I've written that discuss this more:

ASP.NET 3.5 also has a new <asp:ListView> control that provides the ability to perform rich data scenarios with total control over the markup.  It works nicely with the new CSS support in VS 2008.  You can learn more about it from my article here:

You can watch some videos that discuss the new Visual Studio 2008 web designer features and the new ListView/DataPager controls here

Language Improvements and LINQ

The new VB and C# compilers in VS 2008 deliver significant improvements to the languages.  Both add functional programming concepts that enable you to write cleaner, terser, and more expressive code.  These features also enable a new programming model we call LINQ (language integrated query) that makes querying and working with data a first-class programming concept with .NET. 

Below are some of the articles I've written that explore these new language features using C#:

Here are a few additional blog posts I've written that show off some of the new VS 2008 code editing support and some cool ways to use these new language features:

The Visual Basic team has also created some great free videos that cover LINQ.  You can watch them here.

Data Access Improvements with LINQ to SQL

LINQ to SQL is a built-in OR/M (object relational mapper) in .NET 3.5.  It enables you to model relational databases using a .NET object model.  You can then query the database using LINQ, as well as update/insert/delete data from it.  LINQ to SQL fully supports transactions, views, and stored procedures.  It also provides an easy way to integrate business logic and validation rules into your data model.  Below are some of the articles I've written that explore how to use it:

I think you'll find that LINQ and LINQ to SQL makes it much easier to build much cleaner data models, and write much cleaner data code.  I'll be adding more posts to my LINQ to SQL series in the weeks and months ahead (sorry for the delay in finishing them earlier - so much to-do and so little time to-do it all!).

Scott Stanfield is also working on creating some great LINQ to SQL videos for the www.asp.net site based on my article series above (all videos are in both VB and C#).  You can watch the first 4 videos in this series here.

Browsing the .NET Framework Library Source using Visual Studio

As I blogged a few weeks ago, we will be releasing a reference version of the .NET Framework library source code as part of this release.  Visual Studio 2008 has built-in debugger support to automatically step-into and debug this code on demand (VS 2008 can pull down the source for the appropriate .NET Framework library file automatically for you).

We are deploying the source servers to enable this right now, and will be publishing the steps to turn this feature on in the next few weeks.

Lots of other improvements

The list above is only a small set of the improvements coming.  For client development VS 2008 includes WPF designer and project support.  ClickOnce and WPF XBAPs now work with FireFox.  WinForms and WPF projects can also now use the ASP.NET Application Services (Membership, Roles, Profile) for roaming user data. 

Office development is much richer - including support for integrating with the Office 2007 ribbon, and with Outlook.  Visual Studio Tools for Office support is also now built-into Visual Studio (you no longer need to buy a separate product).

New WCF and Workflow projects and designers are now included in VS 2008.  Unit testing support is now much faster and included in VS Professional (and no longer just VSTS).  Continuous Integration support is now built-in with TFS.  AJAX web testing (unit and load) is now supported in the VS Test SKU.  And there is much, much more...

Installation Suggestions

People often ask me for suggestions on how best to upgrade from previous betas of Visual Studio 2008.  In general I'd recommend uninstalling the Beta2 bits explicitly.  As part of this you should uninstall Visual Studio 2008 Beta2, .NET Framework Beta2, as well as the Visual Studio Web Authoring Component (these are all separate installs and need to be uninstalled separately).  I then usually recommend rebooting the machine after uninstalling just to make sure everything is clean before you kick off the new install.  You can then install the final release of VS 2008 and .NET 3.5 on the machine.

Once installed, I usually recommend explicitly running the Tools->Import and Export Settings menu option, choosing the "Reset Settings" option, and then re-pick your preferred profile.  This helps ensure that older settings from the Beta2 release are no longer around (and sometimes seems to help with performance).

Note that VS 2008 runs side-by-side with VS 2005 - so it is totally fine to have both on the same machine (you will not have any problems with them on the same box).

Silverlight Tools and VS Web Deployment Project Add-Ins

Two popular add-ins to Visual Studio are not yet available to download for the final VS 2008 release.  These are the Silverlight 1.1 Tools Alpha for Visual Studio and the Web Deployment Project add-in for Visual Studio.  Our hope is to post updates to both of them to work with the final VS 2008 release in the next two weeks.  If you are doing Silverlight 1.1 development using VS 2008 Beta2 you'll want to stick with with VS 2008 Beta2 until this updated Silverlight Tools Add-In is available. 

Hope this helps,

Scott

Monday, March 03, 2008 5:23:57 AM UTC  #    Comments [0]    |   |  Trackback
 Monday, January 07, 2008

http://blog.emanuelebartolesi.com/post/2007/12/Log4net-Simple-way-to-use-in-your-Aspnet-application.aspx

Introduction

Log the actions of your applications is very important especially when you develop new features or develop very difficult logical business.
But it is also important when users use your applications to understand the critical issues or problems.
To implement quickly the log operations Apache developed an opensource library for .Net developers.

Download

You can download the latest version of Log4net from this location.

Add reference to your solution

In Visual Studio 2005 select Project -> Add Reference.
In the tab Browse, find and select the dll Log4net.dll in your local folder.

Modify web.config

Into web.config file add this code into the section Configuration->Configsections:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

Yet, add the section:

<log4net>

<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">

<file value="c:\temp\web.log" />

<appendToFile value="true" />

<maximumFileSize value="1024KB" />

<maxSizeRollBackups value="10" />

<layout type="log4net.Layout.PatternLayout">

<conversionPattern value="%date %level %logger - %message%newline" />

</layout>

</appender>

<root>

<level value="DEBUG" />

<appender-ref ref="RollingFile" />

</root>

</log4net>

In this configuration will create a log file into the folder "c:\temp\" until its size is 1024Kb.
After this size the name of file will be web.log.1 until 10.
At this link you can find another configurations.

Global.asax

In the event "Application_Start" of the file Global.asax add this line:
log4net.Config.XmlConfigurator.Configure();
Begin to log

In every page you want to log something, add the static variable like below:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

This class has 5 levels of severity to log the operations:

log.Debug("log something at this level")
log.Info("log something at this level")
log.Warn("log something at this level");
log.Error("log something at this level");
log.Fatal("log something at this level");

Simple and fast to use.
You find the official documentation at this link.

Monday, January 07, 2008 10:28:47 PM UTC  #    Comments [0]    |   |  Trackback
 Tuesday, November 06, 2007
Show date in english:
ToString("MM/dd", new System.Globalization.CultureInfo("en-us"))

//
// Any source code blocks look like this
//

DateTime dt = DateTime.Now;
String strDate="";
strDate = dt.ToString("MM/dd/yyyy"); // 07/21/2007
strDate = dt.ToString("dddd, dd MMMM yyyy"); //Saturday, 21 July 2007
strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm"); // Saturday, 21 July 2007 14:58
strDate = dt.ToString("dddd, dd MMMM yyyy hh:mm tt"); // Saturday, 21 July 2007 03:00 PM
strDate = dt.ToString("dddd, dd MMMM yyyy H:mm"); // Saturday, 21 July 2007 5:01
strDate = dt.ToString("dddd, dd MMMM yyyy h:mm tt"); // Saturday, 21 July 2007 3:03 PM
strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:04:10
strDate = dt.ToString("MM/dd/yyyy HH:mm"); // 07/21/2007 15:05
strDate = dt.ToString("MM/dd/yyyy hh:mm tt"); // 07/21/2007 03:06 PM
strDate = dt.ToString("MM/dd/yyyy H:mm"); // 07/21/2007 15:07
strDate = dt.ToString("MM/dd/yyyy h:mm tt"); // 07/21/2007 3:07 PM
strDate = dt.ToString("MM/dd/yyyy HH:mm:ss"); // 07/21/2007 15:09:29
strDate = dt.ToString("MMMM dd"); // July 21
strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"); // 2007-07-21T15:11:19.1250000+05:30
strDate = dt.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"); // Sat, 21 Jul 2007 15:12:16 GMT
strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); // 2007-07-21T15:12:57
strDate = dt.ToString("HH:mm"); // 15:14
strDate = dt.ToString("hh:mm tt"); // 03:14 PM
strDate = dt.ToString("H:mm"); // 5:15
strDate = dt.ToString("h:mm tt"); // 3:16 PM
strDate = dt.ToString("HH:mm:ss"); // 15:16:29
strDate = dt.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'"); // 2007-07-21 15:17:20Z
strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:17:58
strDate = dt.ToString("yyyy MMMM"); // 2007 July
Tuesday, November 06, 2007 10:10:34 PM UTC  #    Comments [0]    |  Trackback
 Thursday, October 04, 2007
 Friday, September 28, 2007

When you click datasource in .net, it will drive you crazy when error message "object reference not set to an instance of an object" pops out. It is caused by VS.Net can not load data source configuration file correctly. Solution is that you have to go into exclude the datasource configuration file from your project. Normally it is put under the properties directory in the project.

Friday, September 28, 2007 8:02:42 PM UTC  #    Comments [0]    |   |  Trackback
 Thursday, August 16, 2007
 Tuesday, July 17, 2007
Tuesday, July 17, 2007 9:32:38 PM UTC  #    Comments [0]    |  Trackback
 Thursday, July 12, 2007
 Monday, July 02, 2007

Dim startInfo As System.Diagnostics.ProcessStartInfo
Dim pStart As New System.Diagnostics.Process

startInfo = New System.Diagnostics.ProcessStartInfo("C:\file.exe")

pStart.StartInfo = startInfo
pStart.Start()
pStart.WaitForExit() 'Your code will halt until the exe file has executed.

Monday, July 02, 2007 9:38:15 PM UTC  #    Comments [0]    |  Trackback
 Monday, April 16, 2007

http://www.manifold.net/doc/7x/sql_server_express_...

 

SQL Server Express Edition

The Manifold DVD includes a complete distribution of Microsoft® SQL Server™ 2005 Express Edition. SQL Server Express provides the power of SQL Server to Manifold System users at no additional charge.

Introduction

SQL Server 2005 Express Edition is derived from the same engine upon which Microsoft SQL Server 2005 is built. It is a newer and, in many key ways, better alternative to the SQL Server 2000 Desktop Engine (known as MSDE) distributed in earlier Manifold releases.

When delivered in SQL Server Express form, Microsoft has limited SQL Server in several ways:

§ A database cannot exceed 4 gigabytes in size.

§ SQL Server Express may be installed on a multiple CPU machine, but it will execute (run) only on a single processor or a single processor core if multi-core processors are used.

§ SQL Server Express may be installed on a server with any amount of memory, but will use only up to 1 GB of available RAM memory.

Other than these limitations SQL Server Express provides virtually the full power and breadth of SQL Server capabilities. Although MSDE was limited to no more than five users, SQL Server Express no longer has such an artificial throttle on performance. Within the limits of processor, RAM and maximum database size, SQL Server Express always runs at full speed.

 

SQL Server 2005 Features Comparison

http://www.microsoft.com/sql/prodinfo/features/com...

Note:  If SQL Server 2005 Express is running on Windows XP Home, it is limited to five simultaneous connections. If it is running on Windows 2000 or Windows XP Professional, it is limited to 10 simultaneous connections. However, these are limitations of the operating system and not of SQL Server 2005 Express.

 

Upgrading MSDE 2000 to SQL Server 2005 Express

http://www.microsoft.com/technet/prodtechnol/sql/2...

 

MySQL Community Server

http://dev.mysql.com/downloads/mysql/5.0.html

dual license model: http://www.mysql.com/company/legal/licensing/faq.h...

MySQL Enterprise Basic $595

Monday, April 16, 2007 8:38:08 PM UTC  #    Comments [0]    |  Trackback
 Wednesday, April 11, 2007
  • SQLite (only C/C++ interfaces are provided)
  • Firebird (Previously Borland "interbase"
  • WilsonXmlDbClient (ADO.NET provider simulating database)
  • Microsoft potable database
Wednesday, April 11, 2007 4:02:27 PM UTC  #    Comments [0]    |  Trackback
 Thursday, March 15, 2007
 Monday, March 12, 2007

From: http://www.andymcm.com/dotnetfaq.htm#4.

An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An AppDomain can be destroyed by the host without affecting other AppDomains in the process.

Win32 processes provide isolation by having distinct memory address spaces. This is effective, but expensive. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.

One non-obvious use of AppDomains is for unloading types. Currently the only way to unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful if you create and destroy types on-the-fly via reflection.

Microsoft have an http://www.gotdotnet.com/team/clr/AppdomainFAQ.aspx.

Monday, March 12, 2007 10:00:06 PM UTC  #    Comments [0]    |  Trackback
Copyright © 2010 Kevin Mocha. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: