Code:
/ 4.0 / 4.0 / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / fx / src / DataWeb / Client / System / Data / Services / Client / DataServiceRequest.cs / 1305376 / DataServiceRequest.cs
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// query request object
//
//---------------------------------------------------------------------
namespace System.Data.Services.Client
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
#if !ASTORIA_LIGHT // Data.Services http stack
using System.Net;
#else
using System.Data.Services.Http;
#endif
using System.Xml;
/// non-generic placeholder for generic implementation
public abstract class DataServiceRequest
{
/// internal constructor so that only our assembly can provide an implementation
internal DataServiceRequest()
{
}
/// Element Type
public abstract Type ElementType
{
get;
}
/// Gets the URI for a the query
public abstract Uri RequestUri
{
get;
}
/// The ProjectionPlan for the request, if precompiled in a previous page; null otherwise.
internal abstract ProjectionPlan Plan
{
get;
}
/// The TranslateResult associated with this request
internal abstract QueryComponents QueryComponents
{
get;
}
/// Gets the URI for a the query
/// a string with the URI
public override string ToString()
{
return this.QueryComponents.Uri.ToString();
}
///
/// get an enumerable materializes the objects the response
///
/// context
/// query components
/// Projection plan (if compiled in an earlier query).
/// contentType
/// method to get http response stream
/// atom materializer
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Returning MaterializeAtom, caller will dispose")]
internal static MaterializeAtom Materialize(DataServiceContext context, QueryComponents queryComponents, ProjectionPlan plan, string contentType, Stream response)
{
Debug.Assert(null != queryComponents, "querycomponents");
string mime = null;
Encoding encoding = null;
if (!String.IsNullOrEmpty(contentType))
{
HttpProcessUtility.ReadContentType(contentType, out mime, out encoding);
}
if (String.Equals(mime, XmlConstants.MimeApplicationAtom, StringComparison.OrdinalIgnoreCase) ||
String.Equals(mime, XmlConstants.MimeApplicationXml, StringComparison.OrdinalIgnoreCase))
{
if (null != response)
{
XmlReader reader = XmlUtil.CreateXmlReader(response, encoding);
return new MaterializeAtom(context, reader, queryComponents, plan, context.MergeOption);
}
}
return MaterializeAtom.EmptyResults;
}
///
/// Creates a instance of strongly typed DataServiceRequest with the given element type.
///
/// element type for the DataServiceRequest.
/// constructor parameter.
/// returns the strongly typed DataServiceRequest instance.
internal static DataServiceRequest GetInstance(Type elementType, Uri requestUri)
{
Type genericType = typeof(DataServiceRequest<>).MakeGenericType(elementType);
return (DataServiceRequest)Activator.CreateInstance(genericType, new object[] { requestUri });
}
///
/// Ends an asynchronous request to an Internet resource.
///
/// Element type of the result.
/// Source object of async request.
/// The data service context.
/// The asyncResult being ended.
/// The response - result of the request.
internal static IEnumerable EndExecute(object source, DataServiceContext context, IAsyncResult asyncResult)
{
QueryResult result = null;
try
{
result = QueryResult.EndExecute(source, asyncResult);
return result.ProcessResult(context, result.ServiceRequest.Plan);
}
catch (DataServiceQueryException ex)
{
Exception inEx = ex;
while (inEx.InnerException != null)
{
inEx = inEx.InnerException;
}
DataServiceClientException serviceEx = inEx as DataServiceClientException;
if (context.IgnoreResourceNotFoundException && serviceEx != null && serviceEx.StatusCode == (int)HttpStatusCode.NotFound)
{
QueryOperationResponse qor = new QueryOperationResponse(new Dictionary(ex.Response.Headers), ex.Response.Query, MaterializeAtom.EmptyResults);
qor.StatusCode = (int)HttpStatusCode.NotFound;
return (IEnumerable)qor;
}
throw;
}
}
#if !ASTORIA_LIGHT // Synchronous methods not available
///
/// execute uri and materialize result
///
/// element type
/// context
/// query components for request to execute
/// enumerable of results
internal QueryOperationResponse Execute(DataServiceContext context, QueryComponents queryComponents)
{
QueryResult result = null;
try
{
DataServiceRequest serviceRequest = new DataServiceRequest(queryComponents, this.Plan);
result = serviceRequest.CreateResult(this, context, null, null);
result.Execute();
return result.ProcessResult(context, this.Plan);
}
catch (InvalidOperationException ex)
{
QueryOperationResponse operationResponse = result.GetResponse(MaterializeAtom.EmptyResults);
if (null != operationResponse)
{
if (context.IgnoreResourceNotFoundException)
{
DataServiceClientException cex = ex as DataServiceClientException;
if (cex != null && cex.StatusCode == (int)HttpStatusCode.NotFound)
{
// don't throw
return (QueryOperationResponse)operationResponse;
}
}
operationResponse.Error = ex;
throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
}
throw;
}
}
///
/// Synchronizely get the query set count from the server by executing the $count=value query
///
/// The context
/// The server side count of the query set
internal long GetQuerySetCount(DataServiceContext context)
{
Debug.Assert(null != context, "context is null");
this.QueryComponents.Version = Util.DataServiceVersion2;
QueryResult response = null;
DataServiceRequest serviceRequest = new DataServiceRequest(this.QueryComponents, null);
HttpWebRequest request = context.CreateRequest(this.QueryComponents.Uri, XmlConstants.HttpMethodGet, false, null, this.QueryComponents.Version, false);
request.Accept = "text/plain";
response = new QueryResult(this, "Execute", serviceRequest, request, null, null);
try
{
response.Execute();
if (HttpStatusCode.NoContent != response.StatusCode)
{
StreamReader sr = new StreamReader(response.GetResponseStream());
long r = -1;
try
{
r = XmlConvert.ToInt64(sr.ReadToEnd());
}
finally
{
sr.Close();
}
return r;
}
else
{
throw new DataServiceQueryException(Strings.DataServiceRequest_FailGetCount, response.Failure);
}
}
catch (InvalidOperationException ex)
{
QueryOperationResponse operationResponse = null;
operationResponse = response.GetResponse(MaterializeAtom.EmptyResults);
if (null != operationResponse)
{
operationResponse.Error = ex;
throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
}
throw;
}
}
#endif
///
/// Begins an asynchronous request to an Internet resource.
///
/// source of execute (DataServiceQuery or DataServiceContext
/// context
/// The AsyncCallback delegate.
/// The state object for this request.
/// An IAsyncResult that references the asynchronous request for a response.
internal IAsyncResult BeginExecute(object source, DataServiceContext context, AsyncCallback callback, object state)
{
QueryResult result = this.CreateResult(source, context, callback, state);
result.BeginExecute();
return result;
}
///
/// Creates the result object for the specified query parameters.
///
/// The source object for the request.
/// The data service context.
/// The AsyncCallback delegate.
/// The state object for the callback.
/// Result representing the create request. The request has not been initiated yet.
private QueryResult CreateResult(object source, DataServiceContext context, AsyncCallback callback, object state)
{
Debug.Assert(null != context, "context is null");
HttpWebRequest request = context.CreateRequest(this.QueryComponents.Uri, XmlConstants.HttpMethodGet, false, null, this.QueryComponents.Version, false);
return new QueryResult(source, "Execute", this, request, callback, state);
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// query request object
//
//---------------------------------------------------------------------
namespace System.Data.Services.Client
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
#if !ASTORIA_LIGHT // Data.Services http stack
using System.Net;
#else
using System.Data.Services.Http;
#endif
using System.Xml;
/// non-generic placeholder for generic implementation
public abstract class DataServiceRequest
{
/// internal constructor so that only our assembly can provide an implementation
internal DataServiceRequest()
{
}
/// Element Type
public abstract Type ElementType
{
get;
}
/// Gets the URI for a the query
public abstract Uri RequestUri
{
get;
}
/// The ProjectionPlan for the request, if precompiled in a previous page; null otherwise.
internal abstract ProjectionPlan Plan
{
get;
}
/// The TranslateResult associated with this request
internal abstract QueryComponents QueryComponents
{
get;
}
/// Gets the URI for a the query
/// a string with the URI
public override string ToString()
{
return this.QueryComponents.Uri.ToString();
}
///
/// get an enumerable materializes the objects the response
///
/// context
/// query components
/// Projection plan (if compiled in an earlier query).
/// contentType
/// method to get http response stream
/// atom materializer
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Returning MaterializeAtom, caller will dispose")]
internal static MaterializeAtom Materialize(DataServiceContext context, QueryComponents queryComponents, ProjectionPlan plan, string contentType, Stream response)
{
Debug.Assert(null != queryComponents, "querycomponents");
string mime = null;
Encoding encoding = null;
if (!String.IsNullOrEmpty(contentType))
{
HttpProcessUtility.ReadContentType(contentType, out mime, out encoding);
}
if (String.Equals(mime, XmlConstants.MimeApplicationAtom, StringComparison.OrdinalIgnoreCase) ||
String.Equals(mime, XmlConstants.MimeApplicationXml, StringComparison.OrdinalIgnoreCase))
{
if (null != response)
{
XmlReader reader = XmlUtil.CreateXmlReader(response, encoding);
return new MaterializeAtom(context, reader, queryComponents, plan, context.MergeOption);
}
}
return MaterializeAtom.EmptyResults;
}
///
/// Creates a instance of strongly typed DataServiceRequest with the given element type.
///
/// element type for the DataServiceRequest.
/// constructor parameter.
/// returns the strongly typed DataServiceRequest instance.
internal static DataServiceRequest GetInstance(Type elementType, Uri requestUri)
{
Type genericType = typeof(DataServiceRequest<>).MakeGenericType(elementType);
return (DataServiceRequest)Activator.CreateInstance(genericType, new object[] { requestUri });
}
///
/// Ends an asynchronous request to an Internet resource.
///
/// Element type of the result.
/// Source object of async request.
/// The data service context.
/// The asyncResult being ended.
/// The response - result of the request.
internal static IEnumerable EndExecute(object source, DataServiceContext context, IAsyncResult asyncResult)
{
QueryResult result = null;
try
{
result = QueryResult.EndExecute(source, asyncResult);
return result.ProcessResult(context, result.ServiceRequest.Plan);
}
catch (DataServiceQueryException ex)
{
Exception inEx = ex;
while (inEx.InnerException != null)
{
inEx = inEx.InnerException;
}
DataServiceClientException serviceEx = inEx as DataServiceClientException;
if (context.IgnoreResourceNotFoundException && serviceEx != null && serviceEx.StatusCode == (int)HttpStatusCode.NotFound)
{
QueryOperationResponse qor = new QueryOperationResponse(new Dictionary(ex.Response.Headers), ex.Response.Query, MaterializeAtom.EmptyResults);
qor.StatusCode = (int)HttpStatusCode.NotFound;
return (IEnumerable)qor;
}
throw;
}
}
#if !ASTORIA_LIGHT // Synchronous methods not available
///
/// execute uri and materialize result
///
/// element type
/// context
/// query components for request to execute
/// enumerable of results
internal QueryOperationResponse Execute(DataServiceContext context, QueryComponents queryComponents)
{
QueryResult result = null;
try
{
DataServiceRequest serviceRequest = new DataServiceRequest(queryComponents, this.Plan);
result = serviceRequest.CreateResult(this, context, null, null);
result.Execute();
return result.ProcessResult(context, this.Plan);
}
catch (InvalidOperationException ex)
{
QueryOperationResponse operationResponse = result.GetResponse(MaterializeAtom.EmptyResults);
if (null != operationResponse)
{
if (context.IgnoreResourceNotFoundException)
{
DataServiceClientException cex = ex as DataServiceClientException;
if (cex != null && cex.StatusCode == (int)HttpStatusCode.NotFound)
{
// don't throw
return (QueryOperationResponse)operationResponse;
}
}
operationResponse.Error = ex;
throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
}
throw;
}
}
///
/// Synchronizely get the query set count from the server by executing the $count=value query
///
/// The context
/// The server side count of the query set
internal long GetQuerySetCount(DataServiceContext context)
{
Debug.Assert(null != context, "context is null");
this.QueryComponents.Version = Util.DataServiceVersion2;
QueryResult response = null;
DataServiceRequest serviceRequest = new DataServiceRequest(this.QueryComponents, null);
HttpWebRequest request = context.CreateRequest(this.QueryComponents.Uri, XmlConstants.HttpMethodGet, false, null, this.QueryComponents.Version, false);
request.Accept = "text/plain";
response = new QueryResult(this, "Execute", serviceRequest, request, null, null);
try
{
response.Execute();
if (HttpStatusCode.NoContent != response.StatusCode)
{
StreamReader sr = new StreamReader(response.GetResponseStream());
long r = -1;
try
{
r = XmlConvert.ToInt64(sr.ReadToEnd());
}
finally
{
sr.Close();
}
return r;
}
else
{
throw new DataServiceQueryException(Strings.DataServiceRequest_FailGetCount, response.Failure);
}
}
catch (InvalidOperationException ex)
{
QueryOperationResponse operationResponse = null;
operationResponse = response.GetResponse(MaterializeAtom.EmptyResults);
if (null != operationResponse)
{
operationResponse.Error = ex;
throw new DataServiceQueryException(Strings.DataServiceException_GeneralError, ex, operationResponse);
}
throw;
}
}
#endif
///
/// Begins an asynchronous request to an Internet resource.
///
/// source of execute (DataServiceQuery or DataServiceContext
/// context
/// The AsyncCallback delegate.
/// The state object for this request.
/// An IAsyncResult that references the asynchronous request for a response.
internal IAsyncResult BeginExecute(object source, DataServiceContext context, AsyncCallback callback, object state)
{
QueryResult result = this.CreateResult(source, context, callback, state);
result.BeginExecute();
return result;
}
///
/// Creates the result object for the specified query parameters.
///
/// The source object for the request.
/// The data service context.
/// The AsyncCallback delegate.
/// The state object for the callback.
/// Result representing the create request. The request has not been initiated yet.
private QueryResult CreateResult(object source, DataServiceContext context, AsyncCallback callback, object state)
{
Debug.Assert(null != context, "context is null");
HttpWebRequest request = context.CreateRequest(this.QueryComponents.Uri, XmlConstants.HttpMethodGet, false, null, this.QueryComponents.Version, false);
return new QueryResult(source, "Execute", this, request, callback, state);
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu

This book is available now!
Buy at Amazon US or
Buy at Amazon UK
- OdbcConnectionFactory.cs
- GorillaCodec.cs
- QilDataSource.cs
- RenderTargetBitmap.cs
- CodeLinePragma.cs
- RoutedEventValueSerializer.cs
- NullableConverter.cs
- HttpRawResponse.cs
- SessionPageStateSection.cs
- InkCanvasAutomationPeer.cs
- Font.cs
- UIElementParagraph.cs
- SqlBulkCopyColumnMappingCollection.cs
- InvokeMethodActivity.cs
- WindowsTab.cs
- ScriptingJsonSerializationSection.cs
- NonSerializedAttribute.cs
- ImageList.cs
- Section.cs
- XmlStringTable.cs
- SymbolMethod.cs
- CodeLabeledStatement.cs
- DocumentPageTextView.cs
- SafeTimerHandle.cs
- DateTimeSerializationSection.cs
- DoubleAnimationUsingKeyFrames.cs
- ListItemCollection.cs
- ScrollEvent.cs
- GACMembershipCondition.cs
- Parameter.cs
- AttachedPropertyBrowsableForTypeAttribute.cs
- BrowserDefinitionCollection.cs
- DataSourceControl.cs
- WindowsListViewScroll.cs
- InvokeWebServiceDesigner.cs
- TagMapInfo.cs
- DetailsViewUpdatedEventArgs.cs
- SeekStoryboard.cs
- Trace.cs
- AnimationStorage.cs
- SemanticValue.cs
- CallSiteHelpers.cs
- DataObjectEventArgs.cs
- TextServicesHost.cs
- EventManager.cs
- CacheManager.cs
- ClockGroup.cs
- WindowsListViewGroupHelper.cs
- FilePrompt.cs
- TextLine.cs
- ControlTemplate.cs
- RoleGroup.cs
- AbstractExpressions.cs
- QilList.cs
- IteratorFilter.cs
- HyperLinkStyle.cs
- WorkflowTransactionOptions.cs
- ResolveDuplexAsyncResult.cs
- DesignerVerb.cs
- HwndHostAutomationPeer.cs
- FilterQueryOptionExpression.cs
- RawMouseInputReport.cs
- Thumb.cs
- TextSpan.cs
- DataPointer.cs
- DataGridViewRowPrePaintEventArgs.cs
- TemplateApplicationHelper.cs
- DesignerActionMethodItem.cs
- HttpStreamXmlDictionaryReader.cs
- LogicalMethodInfo.cs
- AutomationProperties.cs
- MarginCollapsingState.cs
- cryptoapiTransform.cs
- ResourceSet.cs
- Font.cs
- ParseElementCollection.cs
- Int16AnimationUsingKeyFrames.cs
- PerformanceCounterPermission.cs
- DataPagerCommandEventArgs.cs
- ResourcesBuildProvider.cs
- Annotation.cs
- CodeAttributeArgumentCollection.cs
- KnownTypeAttribute.cs
- SvcFileManager.cs
- SortQueryOperator.cs
- Operand.cs
- Expr.cs
- IgnoreDataMemberAttribute.cs
- SweepDirectionValidation.cs
- BrowsableAttribute.cs
- OleDbConnectionFactory.cs
- PermissionAttributes.cs
- _IPv6Address.cs
- ComponentResourceKey.cs
- CodeVariableReferenceExpression.cs
- ValueHandle.cs
- SqlInternalConnectionSmi.cs
- httpstaticobjectscollection.cs
- BatchStream.cs
- FunctionNode.cs