Your best source of information and news about Vista hardware, seven and software on the internet

ARTICLES TOP 50 Spyware Virus Vista SOFT Vista HELP

Code

You are currently browsing the articles from MS Windows Vista Compatible Software matching the category Code.

How to handle errors in ASP.NET? – Best Practices & Tips: Tracing, Auditing, Logging Blocks

Exception and Error Handling

When an exception occurs in your ASP.NET application code, you can handle it in a number of ways, but the best approach is a multi-pronged one:
? Catch what you expect:
? Use a Try/Catch around error-prone code. This can always catch specific exceptions that you can deal with, such as System.IO.FileNotFoundException

? Rather than catching exceptions around specific chunks of code at the page level, consider using the page-level error handler to catch specific exceptions that might happen anywhere on the page.

? But prepare for unhandled exceptions:
? Set the Page.Error property if a specific page should show a specific error page for any unhandled exception. This can also be done using the <%@ Page > directive or the code behind the property.
? Have default error pages for 400 and 500 errors set in your web.config.
? Have a boilerplate Application_OnError handler that takes into consideration both specific exceptions that you can do something about, as well as all unhandled exceptions that you may want logged to either the event log, a text file, or other instrumentation mechanism.

The phrase unhandled exception may be alarming, but remember that you don’t do anyone any good catching an exception that you can’t recover from. Unhandled exceptions are okay if they are just that — exceptional. For these situations, rely on global exception handlers for logging and friendly error pages that you can present to the user.

Why try to catch an exception by adding code everywhere if you can catch and log exceptions all in one place? A common mistake is creating a try/catch block around some arbitrary code and catching the least specific exception type — System. Exception. A rule of thumb is, don’t catch any exception that you can’t do anything about. Just because an exception can be thrown by a particular method doesn’t mean you have to catch it. It’s exceptional, remember? Also, there are exception handlers at both the page and the application level. Catch exceptions in these two centralized locations rather than all over.

Handling Exceptions on a Page

To handle exceptions at a page level, override the OnError method that System.Web.UI.Page inherits from the TemplateControl class (see Listing 24-5). Calling Server.GetLastError gives you access to the exception that just occurred. Be aware that a chain of exceptions may have occurred, and you can use the ExceptionGetBaseException method to return the root exception.

Page-level error handling

protected override void OnError(EventArgs e)
{
  System.Exception anError = Server.GetLastError();
  if (anError.GetBaseException() is SomeSpecificException)
  {
       Response.Write("Something bad happened!");
       Response.StatusCode = 200;
       Server.ClearError();
       Response.End();
   }
}

Handling Application Exceptions

The technique of catching exceptions in a centralized location can be applied to error handling at the application level in Global.asax, as shown in Listing 24-6. If an exception is not caught on the page, the web.config is checked for an alternate error page; if there isn’t one, the exception bubbles up to the application and your user sees a complete call stack.

Application-level error handling

protected void Application_Error(Object sender, EventArgs e)
{
     System.Exception bigError = Server.GetLastError();
     //Example checking for HttpRequestValidationException
     if(bigError.GetBaseException() is HttpRequestValidationException )
     {
                    System.Diagnostics.Trace.WriteLine(bigError.ToString());
                    Server.ClearError();
      }
}

Unhandled application errors turn into HTTP Status Code 500 and display errors in the browser. These errors, including the complete callstack and other technical details, may be useful during development, but are hardly useful at production time. Most often, you want to create an error handler (as shown previously) to log your error and to give the user a friendlier page to view.

If you ever find yourself trying to catch exceptions of type System.Exception, take a look at the code to see whether you can avoid it. There’s almost never a reason to catch such a non-specific exception, and you’re more likely to swallow exceptions that can provide valuable debugging. Check the API documentation for the framework method you are calling — a section specifically lists what exceptions an API call might throw. Never rely on an exception occurring to get a standard code path to work.

Http Status Codes

Every HttpRequest results in an HttpResponse, and every HttpResponse includes a status code. The following table describes 11 particularly interesting HTTP status codes.

Status Code Explanation

200 OK Everything went well.
301 Moved Permanently
Reminds the caller to use a new, permanent URL rather than the one he used to get here.
302 Found Returned during a Response.Redirect. This is the way to say ‘‘No, no, look over here right now.’’
304 Not Modified
Returned as the result of a conditional GET when a requested document hasn’t been modified. It is the basis of all browser-based caching. An HTTP message-body must not be returned when using a 304.
307 Temporary Redirect
Redirects calls to ASMX Web services to alternate URLs. Rarely used with ASP.NET.
400 Bad Request
Request was malformed.
401 Unauthorized
Request requires authentication from the user.
403 Forbidden Authentication has failed, indicating that the server understood the requests but cannot fulfill it.
404 Not Found The server has not found an appropriate file or handler to handle this request. The implication is that this may be a temporary state. This happens in ASP.NET not only because a file cannot be found, but also because it may be inappropriately mapped to an IHttpHandler that was not available to service the request.
410 Gone The equivalent of a permanent 404 indicating to the client that it should delete any references to this link if possible. 404s usually indicate that the server does not know whether the condition is permanent.

500 Internal Server Error
The official text for this error is ‘‘The server encountered an unexpected condition which prevented it from fulfilling the request,’’ but this error can occur when any unhandled exception bubbles all the way up to the user from ASP.NET.

Any status code greater than or equal to 400 is considered an error and, unless you configure otherwise, the user will likely see an unfriendly message in his browser. If you have not already handled these errors inside of the ASP.NET runtime by checking their exception types, or if the error occurred outside of ASP.NET and you want to show the user a friendly message, you can assign pages to any status code within web.config, as the following example shows:

<customErrors mode ="On" >
     <error statusCode ="500" redirect ="FriendlyMassiveError.aspx" />
</customErrors>

After making a change to the customer errors section of your web.config, make sure a page is available to be shown to the user. A classic mistake in error redirection is redirecting the user to a page that will cause an error, thereby getting him stuck in a loop. Use a great deal of care if you have complicated headers or footers in your application that might cause an error if they appear on an error page. Avoid hitting the database or performing any other backend operation that requires either user authorization or that the user’s session be in any specific state. In other words, make sure that the error page is a reliable standalone.

Any status code greater than or equal to 400 increments the ASP.NET Requests Failed performance counter. 401 increments Requests Failed and Requests Not Authorized. 404 and 414 increment both Requests Failed and Requests Not Found. Requests that result in a 500 status code increment Requests Failed and Requests Timed Out. If you’re going to return status codes, you must realize their effects and their implications.


Filed under: .NET, ASP.NET, Code, Design, Reference, Web Tagged: .NET4, ASP.NET, Attacks, Auditing, Books, Errors, Exceptions, Logging Blocks, MS, Practices, Security, Tips, Tracing

Written by Visitor Blogs on June 8th, 2010 with no comments.
Read more articles on .NET4 and reference and ms and books and Practices and Auditing and Logging Blocks and Attacks and Tracing and otherSoftware and errors and Web and Web and Code and Tips and .Net and exceptions and Design and ASP.NET and Security.

Tips, Tricks, Notes on Entity Frameworks 4.0

The Entity Framework enables you to query, insert, update, and delete data, expressed as typed common language runtime (CLR) objects that are instances of entity types. The entity types represent the entities defined in the conceptual model. The Entity Framework maps entities and relationships that are defined in a conceptual model to a data source. The Entity Framework provides facilities to do the following: materialize data returned from the data source as objects; track changes that were made to the objects; handle concurrency; propagate object changes back to the data source; and bind objects to controls. You can use LINQ to Entities, Entity SQL Language, or Query Builder Methods (Entity Framework) to execute queries against the conceptual model.

Customizable Code-Generation: EF4 leverages the T4 code generation templating engine in Visual Studio. You can now write your own templates that specify exactly how you want code generation to happen; or you can modify the built-in templates such as the Entity Object Code Generator or Self Tracking Entities Code Generator templates: http://blogs.msdn.com/adonet/archive/2009/05/19/sneak-peek-using-code-generation-templates-with-the-entity-framework-4-0.aspx

Self-Tracking Entities & N-Tier support: Visual Studio 2010 includes code-generation templates for Self Tracking Entities that allow you to easily build N-Tier applications. There are also new APIs in the product that offer you more control in N-Tier scenarios. : http://msdn.microsoft.com/en-us/library/ee789839(v=VS.100).aspx

Model Defined Functions LINQ support: Model Defined Functions allow you to define composable functions in your model using Entity SQL. http://blogs.msdn.com/adonet/archive/2009/05/14/sneak-preview-model-defined-functions.aspx

EntityDataSource support for QueryExtender, POCO and FKs: EntityDataSource control now includes support for ASP.NET QueryExtender and POCO entities. QueryExtender is a new addition to ASP.NET, which allows you to have more control over the data retrieval query of a Data Source while leveraging LINQ capabilities of EF.

The Entity Data Model Tools can generate a class derived from ObjectContext that represents the entity container in the conceptual model. This object context provides the facilities for tracking changes and managing identities, concurrency, and relationships. This class also exposes a SaveChanges method that writes inserts, updates, and deletes to the data source. Like queries, these changes are either made by commands automatically generated by the system or by stored procedures that are specified by the developer.

The EntityClient provider extends the ADO.NET provider model by accessing data in terms of conceptual entities and relationships. It executes queries that use Entity SQL. Entity SQL provides the underlying query language that enables EntityClient to communicate with the database

——————————————————————————————————————————-
•Address

•Contact

•Product

•SalesOrderDetail

•SalesOrderHeader

——————————————————————————————————————————-
QueryExtender and Model-Defined Functions
ADO.NET EntityObject Generator

——————————————————————————————————————————-

http://blogs.msdn.com/efdesign/archive/2009/01/22/customizing-entity-classes-with-t4.aspx

ADO.NET Entity Designer generates classes from the CSDL portion of the EDMX file using the EntityClassGenerator APIs.
how to customize the code generation for a variety of scenarios:

Make the generated ObjectContext internal
Make the generated ObjectContext and Entity classes implement a user-defined interface
Add user-defined CLR attributes to generated ObjectContext and generated Entity classes
Influence generated classes based on structural annotations in CSDL
Generate the ObjectContext and Entity classes into separate files
Generate “proxy classes” for the generated classes
Partially or fully change how classes are generated, maybe even generate additional (non code) artifacts in the project
Completely replace entity framework code generation with custom code
Generate POCO classes from the model to use as a starting point in my applications
Generate self-tracking entity classes

——————————————————————————————————————————-

http://blogs.msdn.com/adonet/archive/2008/01/24/customizing-code-generation-in-the-ado-net-entity-designer.aspx

SSDL – store schema definition language
Mapping specification language (MSL)
TT – Text Templates 4 TT4

http://msdn.microsoft.com/en-us/library/bb126445.aspx

Conceptual schema definition language (CSDL) is an XML-based language that describes the entities, relationships, and functions that make up a conceptual model of a data-driven application. This conceptual model can be used by the Entity Framework or ADO.NET Data Services. The metadata that is described with CSDL is used by the Entity Framework to map entities and relationships that are defined in a conceptual model to a data source. For more information, see SSDL Specification and MSL Specification.

——————————————————————————————————————————-
CSDL is the Entity Framework’s implementation of the Entity Data Model.
In an Entity Framework application, conceptual model metadata is loaded from a .csdl file (written in CSDL) into an instance of the System.Data.Metadata.Edm.EdmItemCollection and is accessible by using methods in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework uses conceptual model metadata to translate queries against the conceptual model to data source-specific commands.

——————————————————————————————————————————-
Entity Data Model Designer (Entity Designer):: http://msdn.microsoft.com/en-us/library/cc716685.aspx
.edmx File Overview.:: http://msdn.microsoft.com/en-us/library/cc982042.aspx
Entity Data Model.: http://msdn.microsoft.com/en-us/library/ee382825.aspx

——————————————————————————————————————————-
The conceptual model metadata can be used to generate the object-layer code for an Entity Framework application. For more information, see Generated Code Overview (Entity Data Model Designer) http://msdn.microsoft.com/en-us/library/cc982041.aspx and How to: Use EdmGen.exe to Generate Object-Layer Code. http://msdn.microsoft.com/en-us/library/cc716790.aspx

——————————————————————————————————————————-
Entity Framework Overview:: http://msdn.microsoft.com/en-us/library/bb399567.aspx
ADO.NET Entity Data Model Tools:: http://msdn.microsoft.com/en-us/library/bb399249.aspx

——————————————————————————————————————————-

ObjectContext.ObjectMaterialized Event

This event is raised after all scalar, complex, and reference properties have been set on an object, but before collections are loaded. If an object with the same key value exists in the object context, the Entity Framework will not recreate the object and this event will not be raised.

——————————————————————————————————————————-

ObjectContext Class

Provides facilities for querying and working with entity data as objects.

The ObjectContext class is the primary class for interacting with data as objects that are instances of entity types that are defined in a conceptual model. An instance of the ObjectContext class encapsulates the following:

•A connection to the database, in the form of an EntityConnection object.

•Metadata that describes the model, in the form of a MetadataWorkspace object.

•An ObjectStateManager object that manages objects persisted in the cache.   tracks objects during create, update, and delete operations

When the object layer that represents a conceptual model is generated by the Entity Data Model tools, the class that represents the EntityContainer for the model is derived from the ObjectContext.

EntityObject
By default, the ADO.NET Entity Data Model tools generate EntityObject derived entity types. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework. If you are working with architectures that require persistence ignorance (for example, test- driven development or domain-driven development) or you have existing domain classes, consider using POCO or POCO proxies.

Self-Tracking Entities
The EntityObjectderived types, POCO, and POCO proxy types work well in applications where entity objects can be attached to the object context that handles change tracking. However, when you have to transfer full graphs of entities to a tier where the object context is not available, you must decide how to track changes and report those changes back to the object context. Starting with the .NET Framework version 4, self-tracking entities can record changes to scalar, complex, and navigation properties. Self-tracking entities do not depend on the Entity Framework. The ADO.NET Self-Tracking Entity Generator template generates self-tracking entities

——————————————————————————————————————————-
——————————————————————————————————————————-

// Create the ObjectContext.
ObjectContext context =
 new ObjectContext("name=AdventureWorksEntities");
// Set the DefaultContainerName for the ObjectContext.
// When DefaultContainerName is set, the Entity Framework only
// searches for the type in the specified container.
// Note that if a type is defined only once in the metadata workspace
// you do not have to set the DefaultContainerName.
context.DefaultContainerName = "AdventureWorksEntities";
ObjectSet<Product> query = context.CreateObjectSet<Product>();
// Iterate through the collection of Products.
foreach (Product result in query)
 Console.WriteLine("Product Name: {0}", result.Name);
-------------------------------------------------------------------------------------------------------------------------------

——————————————————————————————————————————-

http://blogs.msdn.com/adonet/archive/2008/01/24/sampleedmxcodegenerator-sources.aspx

How to add custom attributes to my generated classes

——————————————————————————————————————————-
“Database Script Generation” properties:

Database Generation Workflow – Controls the overall process by which the conceptual model is translated into a database script. The default workflow is “TablePerTypeStrategy.xaml”.

DDL Generation Template – Is called by the default database generation workflow to transform the generated database model to DDL. More on this below.

First, let’s take a look at TablePerTypeStrategy.xaml – it is located in Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen. If we open this file in Visual Studio, we see that it is a Workflow Foundation (WF) workflow

The first activity, “CsdlToSsdlAndMslActivity” generates the store model (SSDL) for the EDM, and then generates the mappings (MSL) that connect the two. It has the following properties

The “MslOutputGeneratorType” specifies a class that generates MSL based on a table-per-type mapping strategy. The “OuputGeneratorType” generates SSDL. Rather than replacing this activity and all of the plumbing it provides, you can replace these two classes with your own if you want to change the mapping strategy or otherwise alter the system.

http://blogs.msdn.com/adonet/archive/2009/11/05/model-first-with-the-entity-framework-4.aspx

——————————————————————————————————————————-

Query builder methods

These methods of ObjectQuery enable you to construct queries that are the same as Entity SQL without having to construct a query string. Because these methods always return an ObjectQuery, you can build queries by calling methods in series or use them to extend an Entity SQL query. Some methods, such as Where and OrderBy, take Entity SQL fragments as parameters. Query builder methods can be followed by certain LINQ standard query operators

The ObjectQuery generic class represents a query that can return a collection of zero or more typed objects. An ObjectQuery belongs to an ObjectContext that contains the connection and metadata information that is necessary to compose and execute the query. You can construct an ObjectQuery with a new operator and pass a query string and the object context to the constructor. However, a more common scenario is to use properties on an ObjectContext derived class to get an ObjectQuery instance that represents a collection of entity sets. Typically, the ObjectContext is subclassed, either by a class generated by the Entity Framework tools or by your POCO classes, and the properties on the object context return entity sets as either an ObjectQuery (in .NET Framework version 3.5 SP1) or as an ObjectSet (in .NET Framework version 4). The ObjectSet class extends the ObjectQuery class to provide functionality, such as adding and deleting objects, in the context of a typed entity set.

This is the query builder method example.

string firstName = @"Frances";
string lastName = @"Adams";

using (AdventureWorksEntities context =
 new AdventureWorksEntities())
{
 // Get the contacts with the specified name.
 ObjectQuery<Contact> contactQuery = context.Contacts
 .Where("it.LastName = @ln AND it.FirstName = @fn",
 new ObjectParameter("ln", lastName),
 new ObjectParameter("fn", firstName));

 // Iterate through the collection of Contact items.
 foreach (Contact result in contactQuery)
 Console.WriteLine("Last Name: {0}; First Name: {1}",
 result.LastName, result.FirstName);
}

An object query is executed when:

•It is enumerated by a foreach (C#) or For Each (Visual Basic) statement.

•It is enumerated by a collection operation such as ToArray, ToDictionary or ToList.

•The Execute method is explicitly called.

•LINQ operators such, as First or Any are specified in the outermost part of the query. For more information, see Query Builder Methods (Entity Framework).

Note, if as a result of a query execution, nothing was returned from the data source, the results will contain an empty collection and not a null.

——————————————————————————————————————————-
Entity Framework Features Not Supported by the Entity Designer
The following are Entity Framework features that are not currently supported by the Entity Designer.

•Multiple entity sets per type.

•Creating entity sets for non-root types.

•Table-per-concrete class mapping.

•Using EntityType properties in mapping conditions.

•Unmapped abstract types. When you create an abstract entity type with the Entity Designer, the type must be mapped to a table or view.

•Creating conditions on association mappings.

•Mapping associations directly to stored procedures. Mapping many-to-many associations is not supported. You can indirectly map other associations to stored procedures along with entity types by mapping the appropriate navigation properties to stored procedure parameters.

•Creating conditions on Function Import mappings.

•Annotations.

•Query views.

•Models that contain references to other models.

•Creating associations without corresponding navigation properties.

•Adding or editing storage model objects. (Deleting storage model objects is supported.)

•Adding, editing, or deleting functions that are defined in the conceptual model.

————————————————————————————————————————

Building N-Tier Applications (Entity Framework)

Entity types generated by the Entity Data Model generator tool (EdmGen.exe) and the Entity Data Model Wizard have SerializableAttribute and DataContractAttribute applied. This enables objects to be serialized by using binary serialization, XML serialization, and Windows Communication Foundation (WCF) data contract serialization.

Extending Partial Classes :: How to: Customize Generated Data Objects (Entity Framework).
When data classes are generated by the Entity Data Model tools, they are implemented in partial classes. You can add functionality to objects by extending the generated partial data classes. Having partial classes enables you to extend these classes with custom methods and properties in a separate source file without having to worry about losing your customization when the generated files are refreshed.

——————————————————————————————————————————-

Managing Connections and Transactions

By default, the Entity Framework manages the connection to the database. However, you can manually manage both connections and transactions in your Entity Framework application.

By default, the Entity Framework implements an optimistic concurrency model.  This means that locks are not held on data in the data source between when the data is queried and the data is updated. The Entity Framework saves object changes to the database without checking for concurrency. For entities that might experience a high degree of concurrency, we recommend that the entity define a property in the conceptual layer with an attribute of ConcurrencyMode=”fixed”

When this attribute is used, the Entity Framework checks for changes in the database before saving changes to the database. Any conflicting changes will cause an OptimisticConcurrencyException.

An OptimisticConcurrencyException can also occur when you define an Entity Data Model that uses stored procedures to make updates to the data source. In this case, the exception is raised when the stored procedure that is used to perform updates reports that zero rows were updated.

You may choose to use transactions as an alternative to optimistic concurrency.

The Entity Framework opens connections only when required, for example to execute a query or to call SaveChanges, and then closes the connection when the operation is complete.

Calling any of the following methods opens the connection:

•SaveChanges or Refresh on ObjectContext.

•FirstOrDefault, or First on ObjectQuery.

•Load on EntityCollection.

•Load on EntityReference.

•Any Language-Integrated Query (LINQ) method or ObjectQuery query builder method, such as Where, OrderBy, or Select.

When a query method is called, the connection is opened, and it remains open until the ObjectResult has been completely consumed or disposed.

The Entity Framework supports automatic transaction enlistment. This means that activities performed within an object context, such as executing queries and saving changes to data in the data source, can be isolated in the data source by executing the operation within a System.Transactions transaction. Transactions are used in the Entity Framework to do the following actions:

•To execute multiple operations against the data source that must be highly consistent, such as queries that depend on the successful completion of object changes.

•To coordinate changes in the object context with other distributed operations, such as sending an e-mail notification or writing to a message queue.

Transactions that require the enlistment of additional resource managers are called distributed transactions. Distributed transactions use a distributed transaction coordinator (DTC) to manage the resources that are required to complete the transaction. Promotion of a transaction to a DTC can be a relatively expensive process to establish and complete. Some resource managers, like SQL Server 2005, support the Promotable Single Phase Enlistment (PSPE) transaction protocol. This allows a resource manager to host a transaction that can later be escalated to be managed by the distributed transaction coordinator (DTC) if necessary.

——————————————————————————————————————————-

•When you call SaveChanges, if a current transaction exists, the Entity Framework uses this transaction for operations against the data source. Otherwise, it creates a new transaction for the operation. You can define transactions by using EntityTransaction, Transaction, or TransactionScope.

•Promotion of a transaction to a DTC may occur when a connection is closed and reopened within a single transaction. Because the Entity Framework opens and closes the connection automatically, you should consider manually opening and closing the connection to avoid transaction promotion.

To enlist in an existing transaction, the Entity Framework might close and reopen the connection.

——————————————————————————————————————————-

This example defines a TransactionScope. The TransactionScope ensures that changes to objects in the object context are coordinated with a message queue. The Entity Framework uses this transaction when it saves changes to the database. When an UpdateException occurs, the operation is retried up to two times. When the operation succeeds, the changes in the object context are accepted. For more information, see Managing Connections and Transactions (Entity Framework).

This example uses a long-running object context, which is disposed after the transaction succeeds or after all retries have been attempted.
——————————————————————————————————————————-

http://msdn.microsoft.com/en-us/library/bb896325.aspx

The following considerations apply when you use transactions with the Entity Framework:

•Only operations against the data source are transacted. Changes made to objects in the object context are not transacted. Changes to objects in the context are visible outside the transaction scope.

•When the Entity Framework creates a new transaction for a SaveChanges operation, changes to objects in the object context are not accepted until the transaction completes. This ensures that the state of the object context and the data source are consistent.

•When you plan to retry operations in a transaction, you must ensure that the status of objects in the context is not reset before the transaction is completed. To do this, you must call SaveChanges with a value of false for the acceptChangesDuringSave parameter, and then call AcceptAllChanges only after other operations in the transaction have completed successfully.

——————————————————————————————————————————-

Managing Transactions

In the Entity Framework, there are two ways to use transactions: automatic and explicit. Automatic transactions use the System.Transactions namespace, and explicit transactions use the EntityTransaction class.


Filed under: ASP.NET, Code, Database, Reference Tagged: .NET, ADO.NET, ASP, C#, Code, data Access, Data Services, EF4, Entity, Feeds, Frameworks, OData, RIA, RSS, SQL, SQL Server, WCF

Written by Visitor Blogs on May 20th, 2010 with no comments.
Read more articles on Frameworks and Entity and EF4 and ADO.NET and ASP and RIA and data Access and Data Services and OData and reference and SQL Server and SQL and ASP.NET and .Net and Code and WCF and feeds and otherSoftware and Database and c# and RSS.

Programming Entity Framework

Building Data Centric Apps with the ADO.NET Entity Framework

By
Julia Lerman

Examples

http://apress.com/book/view/1430227036

Source Code

http://rapidshare.com/files/267643644/Wrox.Professional.ADO.NET.3.5.with.LINQ.and.the.Entity.Framework.Feb.2009.rar

Source Code ::

http://apress.com/book/view/9781590599907

I’ve been using a lot of NoTracking queries to grab lists of data that I don’t need change tracked. One of the interesting behaviors of EF4’s Lazy Loading is that even if you have entities that you have queried with NoTracking on, they will still lazy load related entities.

http://learnentityframework.com/

SELECT VALUE BAModel.Contact(c.ContactID,c.FirstName,c.LastName,c.Title,c.AddDate,c.ModifiedDate)
FROM dbo.Contact as c
WHERE c.AddDate>=”1/1/2007″

I was trying to emulate T-SQL here but I need a date, not a string. I thought that without a function I was hosed again, until I discovered Entity SQL’s Literals and rewrote the query successfully this way.

SELECT VALUE BAModel.Contact(c.ContactID,c.FirstName,c.LastName,c.Title,c.AddDate,c.ModifiedDate)
FROM dbo.Contact as c
WHERE c.AddDate>= DATETIME’2007-01-1 00:00′

I’ve had  number of emails recently with people using Entity SQL and having problems similar to this, most commonly with decimals & doubles (e.g., 123.24). First I will point you to the MSDN documentation page on Literals for Entity SQL.

this ESQL expression will fail:

select p.amount from BAEntities.Payments as p where p.amount=125.25

The exception message is “The argument types ‘Edm.Decimal’ and ‘Edm.Double’ are incompatible for this operation. Near WHERE predicate, line 1, column 61.

Entity Framework POCO Template for .NET 3.5

Funky Behavior NoTracking Query Entities

Entity Framework Profiler’s Beta period ends tomorrow when it goes RTM. But that means the 30% discount also ends. It will go from $220US to $315US tomorrow.

I spend a lot of time looking at what’s going on in my database when using EF and the views that EFProf provide are indispensible. It’s organized by context instance and provides links back to the .NET code that executed each command.

  1. Agile Entity Framework 4 Repository: Part 1- Model and POCO Classes
  2. Agile Entity Framework 4 Repository: Part 2- The Repository
  3. Agile EF4 Repository: Part 3 -Fine Tuning the Repository
  4. Agile EF4 Repository: Part 4: Compiled LINQ Queries
  5. Agile Entity Framework 4 Repository Part 5: IObjectSet and Include
  6. Agile Entity Framework 4 Repository: Part 6: Mocks & Unit Tests

Data Access

Entity Framework Lazy Loading by Context or by Property?

Defining Constraints in an EF4 model that don’t exist in the database

Entity Framework ObjectContext and Reporting

,

1.
Chapter 1 Introducing the ADO.NET Entity Framework
1.
Programming Against a Model, Not Against the Database
2.
The Entity Data Model: A Client-Side Data Model
3.
The Entity in “Entity Framework”
4.
Choosing Your Backend
5.
Entity Framework Features
6.
The Entity Framework in Web Services
7.
What About ADO.NET DataSets and LINQ to SQL?
8.
Entity Framework Pain Points
9.
Programming the Entity Framework
2.
Chapter 2 Exploring the Entity Data Model
1.
Why Use an Entity Data Model?
2.
The EDM Within the Entity Framework
3.
Your First EDM
4.
The EDM in the Designer Window
5.
Entity Properties
6.
The Naked Model: Inspecting the Model’s XML
7.
A Less Daunting Model View
8.
The Three Parts of the Model
9.
CSDL: The Conceptual Schema
10.
SSDL: The Store Schema
11.
MSL: The Mappings
12.
Database Views in the EDM
13.
Code Generation from EDM to Classes
14.
Summary
3.
Chapter 3 Querying Entity Data Models
1.
Query the Model, Not the Database
2.
Your First EDM Query
3.
LINQ to Entities Queries
4.
Entity SQL Queries That Return Objects
5.
Method-Based Syntax Queries for LINQ and Entity SQL
6.
The Shortest Query
7.
EntityClient: The Lowest-Level Method for Returning Streamed Data Through EDM Queries
8.
Translation to Database Queries
9.
Avoid Inadvertent Query Execution
10.
Summary
4.
Chapter 4 Exploring EDM Queries in Greater Depth
1.
Same Model, Friendlier Name
2.
Projections in Queries
3.
Projections in Entity SQL
4.
Querying Across Associations
5.
Joins and Nested Queries
6.
Grouping
7.
Shaped Data Returned by Queries
8.
Deferred Loading and Eager Loading Queries
9.
Retrieving a Single Entity
10.
Retrieving a Single Entity with GetObjectByKey
11.
Entity SQL’s Wrapped and Unwrapped Results
12.
Summary
5.
Chapter 5 Modifying Entities and Saving Changes
1.
How ObjectContext Manages Entities
2.
The SaveChanges Method
3.
Adding New Entities
4.
Inserting New Parents and Children
5.
Deleting Entities
6.
Summary
6.
Chapter 6 Using Stored Procedures with the EDM
1.
Adding the Stored Procedures into the Model
2.
Working with Functions
3.
Implementing Functions
4.
The EDM Designer’s Model Browser
5.
Mapping the Last of the Four Functions: CustomersbyState
6.
More About the Update Model Wizard
7.
Summary
7.
Chapter 7 Tuning Up a Model
1.
The BreakAway Geek Adventures Business Model
2.
Creating a Class Library Project to Host an EDM
3.
Inspecting and Cleaning Up a New Model
4.
Cleaning Up Navigation Property Names
5.
Mapping a Few Stored Procedures
6.
Working with Many-to-Many Relationships
7.
Building the BreakAwayModel Project
8.
Summary
8.
Chapter 8 Data Binding with Windows Forms and WPF Applications
1.
Data Binding with Windows Forms Applications
2.
Data Binding with WPF Applications
3.
Summary
9.
Chapter 9 Working with Object Services
1.
Where Does Object Services Fit into the Framework?
2.
Query Processing
3.
Object Materialization
4.
The ObjectContext
5.
State Management and ObjectStateEntry
6.
Relationship Management
7.
Sending Changes Back to the Database
8.
Additional Features
9.
Summary
10.
Chapter 10 Customizing Entities
1.
Partial Classes
2.
Customizable Methods
3.
Customizable Event Handlers
4.
Other Opportunities for Customization
5.
Summary
11.
Chapter 11 Using the ASP.NET EntityDataSource Control
1.
Getting to First Base with the EntityDataSource Control and Flat Data
2.
Understanding How the EntityDataSource Is Able to Retrieve and Update Your Data
3.
Working with Related EntityReference Data
4.
Working with Hierarchical Data in a Master/Detail Form
5.
Browsing Through the EntityDataSource Events
6.
Summary
12.
Chapter 12 Customizing Entity Data Models
1.
Designer Support for Mappings
2.
Mapping Table per Type Inheritance for Tables That Describe Derived Types
3.
Using Entity Splitting to Map a Single Entity to More Than One Table
4.
Using Conditional Mapping to Filter Entity Mappings
5.
Implementing Table per Hierarchy Inheritance for Tables That Contain Multiple Types
6.
Implementing Customizations That Are Not Supported by the EDM Designer
7.
Mapping Table per Concrete (TPC) Type Inheritance for Tables with Overlapping Fields
8.
Creating Complex Types to Encapsulate Sets of Properties
9.
Using QueryView to Create Read-Only Entities and Other Specialized Mappings
10.
Additional Customization Options
11.
Summary
13.
Chapter 13 Working with Stored Procedures When Function Mapping Won’t Do
1.
Does the Procedure Line Up with an Entity?
2.
Overview of Procedures, UDFs, and TVFs in the EDM
3.
Composing Queries Against Functions
4.
Mapping and Executing Query Stored Procedures
5.
Adding Native Queries to the Model
6.
Adding Native Views to the Model
7.
Using Commands That Affect the Persisted Database
8.
Defining Insert, Update, and Delete Stored Procedures Directly in the Model
9.
Mapping Insert/Update/Delete to Types Within an Inheritance Structure
10.
Implementing and Querying with User-Defined Functions (UDFs)
11.
Summary
14.
Chapter 14 Using Entities with Web and WCF Services
1.
Building a Client That Is Ignorant of the Entity Framework
2.
Using the Entity Framework with ASMX Web Services
3.
Using the Entity Framework with WCF Services
4.
Summary
15.
Chapter 15 Working with Relationships and Associations
1.
Deconstructing Relationships in the Entity Data Model
2.
Deconstructing Relationships Between Instantiated EntityObjects
3.
Defining Relationships Between Entities
4.
Learning a Few Last Tricks to Make You a Relationship Pro
5.
Summary
16.
Chapter 16 Making It Real: Connections, Transactions, Performance, and More
1.
EntityConnection and Database Connections in the Entity Framework
2.
The Entity Framework and Transactions
3.
The Entity Framework and Security
4.
The Entity Framework and Performance
5.
Entities in Multithreaded Applications
6.
Summary
17.
Chapter 17 Controlling Objects with ObjectStateManager and MetadataWorkspace
1.
Managing ObjectStateEntry Objects with ObjectStateManager
2.
Getting an ObjectStateManager and Its Entries
3.
CurrentValues and OriginalValues
4.
Building the ObjectStateEntry Visualizer
5.
ObjectStateManager and SavingChanges
6.
The MetadataWorkspace API
7.
Creating EntityObjects Without Entity Classes
8.
Creating Entities and Graphs Dynamically
9.
Summary
18.
Chapter 18 Handling Entity Framework Exceptions
1.
Preparing for Exceptions in Entity Framework Code
2.
EntityConnectionString Exceptions
3.
Query Compilation Exceptions
4.
Creating a Common Wrapper to Handle Query Execution Exceptions
5.
SaveChanges Command Execution Exceptions
6.
ObjectStateEntries Returned by Object Services Exceptions
7.
InvalidOperationExceptions
8.
Exceptions When Multiple Parties Edit Data Concurrently
9.
Understanding Optimistic Concurrency Options in the Entity Framework
10.
Implementing Optimistic Concurrency with the Entity Framework
11.
Handling OptimisticConcurrencyExceptions
12.
Handling Concurrency Exceptions at a Lower Level
13.
Handling Exceptions When Transactions Are Your Own
14.
Summary
19.
Chapter 19 Using Your Own Custom Classes
1.
Mapping Classes to the Entity Data Model
2.
Implementing the IPOCO Interfaces
3.
Custom Class Assemblies and Entity Data Model Files
4.
Summary
20.
Chapter 20 Using the Entity Framework in n-Tier Client-Side Applications
1.
Thinking in Layers
2.
Finding Your Motivation: A Master/Detail Data Entry Form That Will Use the DataBridge Class
3.
Preventing Non-UI Logic from Leaking into the UI
4.
Implementing Logic That Fits Best in the Entity Partial Classes
5.
Building the CommandExecutor Class
6.
Building the DataBridge Class
7.
Using the DataBridge Class for Data Binding in a Master/Detail Form
8.
Allowing Users to Roll Back Their Edits
9.
Helping the User Who Forgets to Save Changes
10.
Summary
21.
Chapter 21 Using the Entity Framework in n-Tier ASP.NET Applications
1.
Understanding How an ObjectContext Fits into the Web Page Life Cycle
2.
Introducing ASP.NET’s ObjectDataSource Control
3.
Designing Object Provider Classes to Be Used with an ObjectDataSource
4.
Wiring Up the Provider Classes to ObjectDataSource Controls
5.
Understanding Why We Didn’t Use Object Graphs in This Business Layer
6.
Summary
22.
Chapter 22 Implementing a Smarter WCF Service for Working with Entities
1.
Will Your Client Agree to Your Data Contract?
2.
Shipping DTOs, Not EntityObjects
3.
Creating EntityState Properties That Do Not Rely on ObjectContext
4.
Designing the Service Interface
5.
Implementing the Service Operations
6.
Implementing the Client That Will Use the WCF Service
7.
Testing It All with a Simple Console Application
8.
Summary
23.
Chapter 23 The Entity Framework, Today and Tomorrow
1.
What About Building Reports with the Entity Framework?
2.
Extensions, Samples, and Solutions from Microsoft
3.
Entity Framework v.Next
4.
Blogs, Forums, and Other Resources

1.
Appendix Entity Framework Assemblies and Namespaces
1.
Unpacking the Entity Framework Files
2.
Exploring the Namespaces


Filed under: .NET, Blogs, Code, Database, Design, Products, Reference Tagged: .NET, ADO.NET, Books, DAO, Data, DTO, EF4, Entity, Entity Frameworks, Linq, ODBC, Oracle, SQL

Written by Visitor Blogs on May 20th, 2010 with no comments.
Read more articles on Entity and EF4 and ADO.NET and reference and Data and ODBC and Entity Frameworks and DTO and DAO and LINQ and books and .Net and Blogs and Code and SQL and Oracle and otherSoftware and Database and Design and Products.

SQL cookbook By Anthony Molinaro

1 Retrieving Records

1.Retrieving All Rows and Columns from a Table
2.Retrieving a Subset of Rows from a Table
3.Finding Rows That Satisfy Multiple Conditions
4.Retrieving a Subset of Columns from a Table
5.Providing Meaningful Names for Columns
6.Referencing an Aliased Column in the WHERE Clause
7.Concatenating Column Values
8.Using Conditional Logic in a SELECT Statement
9.Limiting the Number of Rows Returned
10.Returning n Random Records from a Table
11.Finding Null Values
12.Transforming Nulls into Real Values
13.Searching for Patterns

2.

2 Sorting Query Results

1.Returning Query Results in a Specified Order
2.Sorting by Multiple Fields
3.Sorting by Substrings
4.Sorting Mixed Alphanumeric Data
5.Dealing with Nulls when Sorting
6.Sorting on a Data Dependent Key

3 Working with Multiple Tables

1.Stacking One Rowset atop Another
2.Combining Related Rows
3.Finding Rows in Common Between Two Tables
4.Retrieving Values from One Table That Do Not Exist in Another
5.Retrieving Rows from One Table That Do Not Correspond to Rows in Another
6.Adding Joins to a Query Without Interfering with Other Joins
7.Determining Whether Two Tables Have the Same Data
8.Identifying and Avoiding Cartesian Products
9.Performing Joins when Using Aggregates
10.Performing Outer Joins when Using Aggregates
11.Returning Missing Data from Multiple Tables
12.Using NULLs in Operations and Comparisons
4.

4 Inserting, Updating, Deleting

1.Inserting a New Record
2.Inserting Default Values
3.Overriding a Default Value with NULL
4.Copying Rows from One Table into Another
5.Copying a Table Definition
6.Inserting into Multiple Tables at Once
7.Blocking Inserts to Certain Columns
8.Modifying Records in a Table
9.Updating when Corresponding Rows Exist
10.Updating with Values from Another Table
11.Merging Records
12.Deleting All Records from a Table
13.Deleting Specific Records
14.Deleting a Single Record
15.Deleting Referential Integrity Violations
16.Deleting Duplicate Records
17.Deleting Records Referenced from Another Table

5.

5 Metadata Queries

1.Listing Tables in a Schema
2.Listing a Table’s Columns
3.Listing Indexed Columns for a Table
4.Listing Constraints on a Table
5.Listing Foreign Keys Without Corresponding Indexes
6.Using SQL to Generate SQL
7.Describing the Data Dictionary Views in an Oracle Database

6.6 Working with Strings

1.Walking a String
2.Embedding Quotes Within String Literals
3.Counting the Occurrences of a Character in a String
4.Removing Unwanted Characters from a String
5.Separating Numeric and Character Data
6.Determining Whether a String Is Alphanumeric
7.Extracting Initials from a Name
8.Ordering by Parts of a String
9.Ordering by a Number in a String
10.Creating a Delimited List from Table Rows
11.Converting Delimited Data into a Multi-Valued IN-List
12.Alphabetizing a String
13.Identifying Strings That Can Be Treated as Numbers
14.Extracting the nth Delimited Substring
15.Parsing an IP Address

7.

7 Working with Numbers

1.Computing an Average
2.Finding the Min/Max Value in a Column
3.Summing the Values in a Column
4.Counting Rows in a Table
5.Counting Values in a Column
6.Generating a Running Total
7.Generating a Running Product
8.Calculating a Running Difference
9.Calculating a Mode
10.Calculating a Median
11.Determining the Percentage of a Total
12.Aggregating Nullable Columns
13.Computing Averages Without High and Low Values
14.Converting Alphanumeric Strings into Numbers
15.Changing Values in a Running Total

8.

8 Date Arithmetic

1.Adding and Subtracting Days, Months, and Years
2.Determining the Number of Days Between Two Dates
3.Determining the Number of Business Days Between Two Dates
4.Determining the Number of Months or Years Between Two Dates
5.Determining the Number of Seconds, Minutes, or Hours Between Two Dates
6.Counting the Occurrences of Weekdays in a Year
7.Determining the Date Difference Between the Current Record and the Next Record

9.

9 Date Manipulation

1.Determining if a Year Is a Leap Year
2.Determining the Number of Days in a Year
3.Extracting Units of Time from a Date
4.Determining the First and Last Day of a Month
5.Determining All Dates for a Particular Weekday Throughout a Year
6.Determining the Date of the First and Last Occurrence of a Specific Weekday in a Month
7.Creating a Calendar

8.Listing Quarter Start and End Dates for the Year

9.Determining Quarter Start and End Dates for a Given Quarter
10.Filling in Missing Dates
11.Searching on Specific Units of Time
12.Comparing Records Using Specific Parts of a Date
13.Identifying Overlapping Date Ranges

10.

10 Working with Ranges

1.Locating a Range of Consecutive Values
2.Finding Differences Between Rows in the Same Group or Partition
3.Locating the Beginning and End of a Range of Consecutive Values
4.Filling in Missing Values in a Range of Values
5.Generating Consecutive Numeric Values
11

11 Advanced Searching

1.Paginating Through a Result Set
2.Skipping n Rows from a Table
3.Incorporating OR Logic when Using Outer Joins
4.Determining Which Rows Are Reciprocals
5.Selecting the Top n Records
6.Finding Records with the Highest and Lowest Values
7.Investigating Future Rows
8.Shifting Row Values
9.Ranking Results
10.Suppressing Duplicates
11.Finding Knight Values
12.Generating Simple Forecasts

12.12 Reporting and Warehousing

1.Pivoting a Result Set into One Row
2.Pivoting a Result Set into Multiple Rows
3.Reverse Pivoting a Result Set
4.Reverse Pivoting a Result Set into One Column
5.Suppressing Repeating Values from a Result Set
6.Pivoting a Result Set to Facilitate Inter-Row Calculations
7.Creating Buckets of Data, of a Fixed Size
8.Creating a Predefined Number of Buckets
9.Creating Horizontal Histograms
10.Creating Vertical Histograms
11.Returning Non-GROUP BY Columns
12.Calculating Simple Subtotals
13.Calculating Subtotals for All Possible Expression Combinations
14.Identifying Rows That Are Not Subtotals
15.Using Case Expressions to Flag Rows
16.Creating a Sparse Matrix
17.Grouping Rows by Units of Time
18.Performing Aggregations over Different Groups/Partitions Simultaneously
19.Performing Aggregations over a Moving Range of Values
20.Pivoting a Result Set with Subtotals

13.

13 Hierarchical Queries

1.Expressing a Parent-Child Relationship
2.Expressing a Child-Parent-Grandparent Relationship
3.Creating a Hierarchical View of a Table
4.Finding All Child Rows for a Given Parent Row
5.Determining Which Rows Are Leaf, Branch, or Root Nodes

14

14 Odds ‘n’ Ends

1.Creating Cross-Tab Reports Using SQL Server’s PIVOT Operator
2.Unpivoting a Cross-Tab Report Using SQL Server’s UNPIVOT Operator
3.Transposing a Result Set Using Oracle’s MODEL Clause
4.Extracting Elements of a String from Unfixed Locations
5.Finding the Number of Days in a Year (an Alternate Solution for Oracle)
6.Searching for Mixed Alphanumeric Strings
7.Converting Whole Numbers to Binary Using Oracle
8.Pivoting a Ranked Result Set
9.Adding a Column Header into a Double Pivoted Result Set
10.Converting a Scalar Subquery to a Composite Subquery in Oracle
11.Parsing Serialized Data into Rows
12.Calculating Percent Relative to Total
13.Creating CSV Output from Oracle
14.Finding Text Not Matching a Pattern (Oracle)
15.Transforming Data with an Inline View
16.Testing for Existence of a Value Within a Group

1.

A Window Function Refresher

1.Grouping
2.Windowing

2.B Rozenshtein Revisited

1.Rozenshtein’s Example Tables
2.Answering Questions Involving Negation
3.Answering Questions Involving “at Most”
4.Answering Questions Involving “at Least”
5.Answering Questions Involving “Exactly”
6.Answering Questions Involving “Any” or “All”


Filed under: Certification, Code, Database Tagged: Books, Contents, Cookbooks, DB2, Index, MS-SQL, MySQL, Oracle, Oreilly, PL/SQL, Refer, Reference, SQL, SQL Server, TOC

Written by Visitor Blogs on May 4th, 2010 with no comments.
Read more articles on MS-SQL and PL/SQL and Refer and TOC and Contents and Oreilly and Cookbooks and DB2 and reference and SQL Server and Oracle and Certification and SQL and Database and otherSoftware and MySQL and Index and books and Code.

Develop for Windows

As developers evolve, so do their applications. And, we are evolving with them. To-date, Windows 7 has sold a record-breaking 90 million licenses making it the fastest selling operating system in history. This creates an awesome opportunity for developers to create some stunning software applications for a vast audience. We’re recognizing that there is an ongoing trend today with developers creating applications that bring together the best of the Web with the best of the Windows. A great example of this is Seesmic for Windows. Seesmic has adopted the Windows Platform as its delivery mechanism today for bringing Twitter to your Windows PC. For geeks like me, Seesmic provides Seesmic for Windows. And for the more casual user, they have Seesmic Look.

We are excited about what we’re seeing from developers like Seesmic and others and are encouraged by the future development of applications on the Windows Platform. There are 3 million developers and the majority target Windows. To help them stay connected with us and the community; we are introducing a new website today called Develop for Windows. We heard feedback from developers that they would like to be able to easily discover important resources for developing for Windows. We are looking to provide just that on the new Develop for Windows website. The new site will allow us to hear from developers and to provide them a single place to find all the resources and tools they can use to build great applications for Windows.

The Develop for Windows website is our direct connection to the developer community, and vice versa. Developers who visit the site will be able to learn about developing for Windows by seeing what’s new with Windows 7, get sample code and special “kits” to jump-start developing a Windows application, and of course pointers to lots and lots of Windows developer content at the Windows Developer Center on MSDN. The Develop for Windows website will also provide special “learning tracks” for developers to experience the technology they are developing for.

We also encourage developers to remain active in the Windows developer community by visiting the Windows forums, learning about local events they should attend and looking at what other developers are building. Microsoft puts on several events each year specifically targeting the developer. This last fall we had PDC09, which allowed developers to attend the Windows Bootcamp and learn about building applications that take advantage of Windows Touch, Sensor and Location Platform and a few other Windows 7 Technologies. Next week, we have MIX10 which is a fantastic event for developers looking to create the types of applications for Windows, mentioned above that bring in the best of the Web with the best of the client experience on Windows.

If you’re developing applications for Windows or looking to begin developing applications for Windows, the new Develop for Windows website is perfect for you. This is just the beginning. We’ll be adding a dedicated social media hub for developers, a developer hero showcase, event content on demand, and fresh videos of developers building innovative applications. Add the site to your Favorites and keep checking back as we’re going to continue to provide updated content on the site based on the feedback we receive from developers. We’ll also have some tips and highlights after MIX10 on Silverlight and Visual Studio 2010 as well!

Written by Brandon LeBlanc on March 10th, 2010 with no comments.
Read more articles on Code7 Contest and Code7 and PDC09 and Sensor and Location Platform and Seesmic for Windows and Seesmic and MIX10 and Develop for Windows and Seesmic Look and Visual Studio 2010 and Windows Developer Center and Windows Touch and windows 7 and msdn and Developers and Visual Studio and otherSoftware and MIX and PDC and Silverlight and Developer and Code.

If you want a menu that shows the contents of the My Computer folder, you already know how to do it

Commenter praful asks what to me is a rather confused question ,
but I’ll try to guess what the real question is. If you drag My Computer to the Start button in XP,
you get an expanding menu that lets you see all files and folders as submenus. Is this Read More……(read more)

Written by The Old New Thing : Code on November 19th, 2007 with no comments.
Read more articles on Code.

« Older articles

No newer articles