private Exception BuildCustomException(Exception ex, DataSourceOperation operation, DbCommand command, out bool isCustomException) { SqlException exception = ex as SqlException; if ((exception != null) && ((exception.Number == 0x89) || (exception.Number == 0xc9))) { string str; if (command.Parameters.Count > 0) { StringBuilder builder = new StringBuilder(); bool flag = true; foreach (DbParameter parameter in command.Parameters) { if (!flag) { builder.Append(", "); } builder.Append(parameter.ParameterName); flag = false; } str = builder.ToString(); } else { str = System.Web.SR.GetString("SqlDataSourceView_NoParameters"); } isCustomException = true; return(new InvalidOperationException(System.Web.SR.GetString("SqlDataSourceView_MissingParameters", new object[] { operation, this._owner.ID, str }))); } isCustomException = false; return(ex); }
protected override ContextDataSourceContextData CreateContext(DataSourceOperation operation) { if (operation == DataSourceOperation.Select) { return(CreateContextAndTableForSelect()); } return(CreateContextAndTableForEdit(operation)); }
protected override ContextDataSourceContextData CreateContext(DataSourceOperation operation) { var tablePropertyInfo = this.ContextType.GetProperty(this.EntitySetName); var result = new ContextDataSourceContextData(Activator.CreateInstance(this.ContextType)); result.EntitySet = tablePropertyInfo.GetValue(result.Context, null); return result; }
protected override ContextDataSourceContextData CreateContext(DataSourceOperation operation) { var tablePropertyInfo = this.ContextType.GetProperty(this.EntitySetName); var result = new ContextDataSourceContextData(Activator.CreateInstance(this.ContextType)); result.EntitySet = tablePropertyInfo.GetValue(result.Context, null); return(result); }
/// <summary>Convenience method. Measures the time if type is non-null, otherwise doesn't measure /// anything.</summary> /// public IDisposable OptionalMeasure(DataSourceOperation op, DataSourceType?type = null) { if (type != null) { return(this[type.Value][op].Measure()); } else { return new ConcurrentStopwatch.Closure { action = () => {} } }; } }
public ConcurrentStopwatch this[DataSourceOperation op] { get { switch (op) { case DataSourceOperation.Read: return(Read); case DataSourceOperation.Write: return(Write); case DataSourceOperation.Delete: return(Delete); default: throw GAssert.LogAndMakeFailureException(); } } }
private ContextDataSourceContextData CreateContextAndTableForEdit(DataSourceOperation operation) { ContextDataSourceContextData contextData = CreateContextAndTable(operation); // context data may be null or incomplete if an exception was handled if (contextData != null) { if (contextData.Context == null) { return(null); } if (contextData.EntitySet == null) { DisposeContext(contextData.Context); return(null); } ValidateContextType(contextData.Context.GetType(), false); ValidateTableType(contextData.EntitySet.GetType(), false); } return(contextData); }
public SqlDataSourceQueryEditorForm(IServiceProvider serviceProvider, SqlDataSourceDesigner sqlDataSourceDesigner, string providerName, string connectionString, DataSourceOperation operation, SqlDataSourceCommandType commandType, string command, IList originalParameters) : base(serviceProvider) { this._sqlDataSourceDesigner = sqlDataSourceDesigner; this.InitializeComponent(); this.InitializeUI(); if (string.IsNullOrEmpty(providerName)) { providerName = "System.Data.SqlClient"; } this._dataConnection = new DesignerDataConnection(string.Empty, providerName, connectionString); this._commandType = commandType; this._commandTextBox.Text = command; this._originalParameters = originalParameters; string str = Enum.GetName(typeof(DataSourceOperation), operation).ToUpperInvariant(); this._commandLabel.Text = System.Design.SR.GetString("SqlDataSourceQueryEditorForm_CommandLabel", new object[] { str }); ArrayList dest = new ArrayList(originalParameters.Count); sqlDataSourceDesigner.CopyList(originalParameters, dest); this._parameterEditorUserControl.AddParameters((Parameter[]) dest.ToArray(typeof(Parameter))); this._commandTextBox.Select(0, 0); switch (operation) { case DataSourceOperation.Delete: this._queryBuilderMode = QueryBuilderMode.Delete; return; case DataSourceOperation.Insert: this._queryBuilderMode = QueryBuilderMode.Insert; return; case DataSourceOperation.Select: this._queryBuilderMode = QueryBuilderMode.Select; return; case DataSourceOperation.Update: this._queryBuilderMode = QueryBuilderMode.Update; return; } }
private ObjectDataSourceMethod GetResolvedMethodData(Type type, string methodName, IDictionary allParameters, DataSourceOperation operation) { bool flag = operation == DataSourceOperation.SelectCount; DataObjectMethodType select = DataObjectMethodType.Select; if (!flag) { select = GetMethodTypeFromOperation(operation); } MethodInfo[] methods = type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); MethodInfo methodInfo = null; ParameterInfo[] infoArray2 = null; int num = -1; bool flag2 = false; int count = allParameters.Count; foreach (MethodInfo info2 in methods) { if (!string.Equals(methodName, info2.Name, StringComparison.OrdinalIgnoreCase) || info2.IsGenericMethodDefinition) { continue; } ParameterInfo[] infoArray3 = info2.GetParameters(); if (infoArray3.Length == count) { bool flag3 = false; foreach (ParameterInfo info3 in infoArray3) { if (!allParameters.Contains(info3.Name)) { flag3 = true; break; } } if (!flag3) { int num4 = 0; if (!flag) { DataObjectMethodAttribute attribute = Attribute.GetCustomAttribute(info2, typeof(DataObjectMethodAttribute), true) as DataObjectMethodAttribute; if ((attribute != null) && (attribute.MethodType == select)) { if (attribute.IsDefault) { num4 = 2; } else { num4 = 1; } } } if (num4 == num) { flag2 = true; } else if (num4 > num) { num = num4; flag2 = false; methodInfo = info2; infoArray2 = infoArray3; } } } } if (flag2) { throw new InvalidOperationException(System.Web.SR.GetString("ObjectDataSourceView_MultipleOverloads", new object[] { this._owner.ID })); } if (methodInfo == null) { if (count == 0) { throw new InvalidOperationException(System.Web.SR.GetString("ObjectDataSourceView_MethodNotFoundNoParams", new object[] { this._owner.ID, methodName })); } string[] array = new string[count]; allParameters.Keys.CopyTo(array, 0); string str = string.Join(", ", array); throw new InvalidOperationException(System.Web.SR.GetString("ObjectDataSourceView_MethodNotFoundWithParams", new object[] { this._owner.ID, methodName, str })); } OrderedDictionary parameters = null; int length = infoArray2.Length; if (length > 0) { parameters = new OrderedDictionary(length, StringComparer.OrdinalIgnoreCase); bool convertNullToDBNull = this.ConvertNullToDBNull; for (int i = 0; i < infoArray2.Length; i++) { ParameterInfo info4 = infoArray2[i]; string name = info4.Name; object obj2 = allParameters[name]; if (convertNullToDBNull && (obj2 == null)) { obj2 = DBNull.Value; } else { obj2 = BuildObjectValue(obj2, info4.ParameterType, name); } parameters.Add(name, obj2); } } return new ObjectDataSourceMethod(operation, type, methodInfo, parameters); }
protected abstract void HandleValidationErrors(IDictionary<string, Exception> errors, DataSourceOperation operation);
private ObjectDataSourceMethod GetResolvedMethodData(Type type, string methodName, Type dataObjectType, object oldDataObject, object newDataObject, DataSourceOperation operation) { int num; MethodInfo[] methods = type.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); MethodInfo methodInfo = null; ParameterInfo[] infoArray2 = null; if (oldDataObject == null) { num = 1; } else if (newDataObject == null) { num = 1; } else { num = 2; } foreach (MethodInfo info2 in methods) { if (string.Equals(methodName, info2.Name, StringComparison.OrdinalIgnoreCase) && !info2.IsGenericMethodDefinition) { ParameterInfo[] parameters = info2.GetParameters(); if (parameters.Length == num) { if ((num == 1) && (parameters[0].ParameterType == dataObjectType)) { methodInfo = info2; infoArray2 = parameters; break; } if (((num == 2) && (parameters[0].ParameterType == dataObjectType)) && (parameters[1].ParameterType == dataObjectType)) { methodInfo = info2; infoArray2 = parameters; break; } } } } if (methodInfo == null) { throw new InvalidOperationException(System.Web.SR.GetString("ObjectDataSourceView_MethodNotFoundForDataObject", new object[] { this._owner.ID, methodName, dataObjectType.FullName })); } OrderedDictionary dictionary = new OrderedDictionary(2, StringComparer.OrdinalIgnoreCase); if (oldDataObject == null) { dictionary.Add(infoArray2[0].Name, newDataObject); } else if (newDataObject == null) { dictionary.Add(infoArray2[0].Name, oldDataObject); } else { string name = infoArray2[0].Name; string a = infoArray2[1].Name; string b = string.Format(CultureInfo.InvariantCulture, this.OldValuesParameterFormatString, new object[] { name }); if (string.Equals(a, b, StringComparison.OrdinalIgnoreCase)) { dictionary.Add(name, newDataObject); dictionary.Add(a, oldDataObject); } else { b = string.Format(CultureInfo.InvariantCulture, this.OldValuesParameterFormatString, new object[] { a }); if (!string.Equals(name, b, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(System.Web.SR.GetString("ObjectDataSourceView_NoOldValuesParams", new object[] { this._owner.ID })); } dictionary.Add(name, oldDataObject); dictionary.Add(a, newDataObject); } } return new ObjectDataSourceMethod(operation, type, methodInfo, dictionary.AsReadOnly()); }
/// <devdoc> /// Builds a custom exception for specific database errors. /// Currently the only custom exception text supported is for SQL Server /// when a parameter is present in the command but not in the parameters /// collection. /// The isCustomException parameter indicates whether a custom exception /// was created or not. This way the caller can determine whether it wants /// to rethrow the original exception or throw the new custom exception. /// </devdoc> private Exception BuildCustomException(Exception ex, DataSourceOperation operation, DbCommand command, out bool isCustomException) { System.Data.SqlClient.SqlException sqlException = ex as System.Data.SqlClient.SqlException; if (sqlException != null) { if ((sqlException.Number == MustDeclareVariableSqlExceptionNumber) || (sqlException.Number == ProcedureExpectsParameterSqlExceptionNumber)) { string parameterNames; if (command.Parameters.Count > 0) { StringBuilder sb = new StringBuilder(); bool firstParameter = true; foreach (DbParameter p in command.Parameters) { if (!firstParameter) { sb.Append(", "); } sb.Append(p.ParameterName); firstParameter = false; } parameterNames = sb.ToString(); } else { parameterNames = SR.GetString(SR.SqlDataSourceView_NoParameters); } isCustomException = true; return new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_MissingParameters, operation, _owner.ID, parameterNames)); } } isCustomException = false; return ex; }
protected override void HandleValidationErrors(IDictionary <string, Exception> errors, DataSourceOperation operation) { }
private int ExecuteDbCommand(DbCommand command, DataSourceOperation operation) { int affectedRows = 0; bool flag = false; try { if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } affectedRows = command.ExecuteNonQuery(); if (affectedRows > 0) { this.OnDataSourceViewChanged(EventArgs.Empty); DataSourceCache cache = this._owner.Cache; if ((cache != null) && cache.Enabled) { this._owner.InvalidateCacheEntry(); } } flag = true; SqlDataSourceStatusEventArgs e = new SqlDataSourceStatusEventArgs(command, affectedRows, null); switch (operation) { case DataSourceOperation.Delete: this.OnDeleted(e); return(affectedRows); case DataSourceOperation.Insert: this.OnInserted(e); return(affectedRows); case DataSourceOperation.Select: return(affectedRows); case DataSourceOperation.Update: this.OnUpdated(e); return(affectedRows); } return(affectedRows); } catch (Exception exception) { bool flag2; if (!flag) { SqlDataSourceStatusEventArgs args2 = new SqlDataSourceStatusEventArgs(command, affectedRows, exception); switch (operation) { case DataSourceOperation.Delete: this.OnDeleted(args2); break; case DataSourceOperation.Insert: this.OnInserted(args2); break; case DataSourceOperation.Update: this.OnUpdated(args2); break; } if (!args2.ExceptionHandled) { throw; } return(affectedRows); } exception = this.BuildCustomException(exception, operation, command, out flag2); if (flag2) { throw exception; } throw; } finally { if (command.Connection.State == ConnectionState.Open) { command.Connection.Close(); } } return(affectedRows); }
/// <summary> /// Evaluates the method parameters using model binding. /// </summary> /// <param name="dataSourceOperation">The datasource operation for which parameters are being evaluated.</param> /// <param name="modelDataSourceMethod">The ModelDataSourceMethod object for which the Parameter collection is being evaluated. The MethodInfo property should already be set on this object.</param> /// <param name="controlValues">The values from the data bound control.</param> /// <param name="isPageLoadComplete">This must be set to true only when this method is called in Page's LoadComplete event handler /// to evaluate the select method parameters that use custom value providers so that we can identify any changes /// to those and mark the data-bound control for data binding if necessary.</param> protected virtual void EvaluateMethodParameters(DataSourceOperation dataSourceOperation, ModelDataSourceMethod modelDataSourceMethod, IDictionary controlValues, bool isPageLoadComplete) { Debug.Assert(_owner.DataControl.Page != null); Debug.Assert(_owner.DataControl.TemplateControl != null); MethodInfo actionMethod = modelDataSourceMethod.MethodInfo; IModelBinder binder = ModelBinders.Binders.DefaultBinder; IValueProvider dataBoundControlValueProvider = GetValueProviderFromDictionary(controlValues); ModelBindingExecutionContext modelBindingExecutionContext = _owner.DataControl.Page.ModelBindingExecutionContext; Control previousDataControl = null; if (BinaryCompatibility.Current.TargetsAtLeastFramework46) { // DevDiv 1087698: a child control overwrites its parent controls's modelBindingExecutionContext, // which may cause a problem for the parent control to find control by controlId. Control dataControl = modelBindingExecutionContext.TryGetService<Control>(); if (dataControl != _owner.DataControl) { previousDataControl = dataControl; } } //This is used by ControlValueProvider later. modelBindingExecutionContext.PublishService<Control>(_owner.DataControl); //This is done for the TryUpdateModel to work inside a Data Method. if (dataSourceOperation != DataSourceOperation.Select) { _owner.DataControl.Page.SetActiveValueProvider(dataBoundControlValueProvider); } var methodParameters = actionMethod.GetParameters(); ParameterInfo lastParameter = null; if (methodParameters.Length > 0) { lastParameter = methodParameters[methodParameters.Length - 1]; } foreach (ParameterInfo parameterInfo in methodParameters) { object value = null; string modelName = parameterInfo.Name; if (parameterInfo.ParameterType == typeof(ModelMethodContext)) { //ModelMethodContext is a special parameter we pass in for enabling developer to call //TryUpdateModel when Select/Update/Delete/InsertMethods are on a custom class. value = new ModelMethodContext(_owner.DataControl.Page); } //Do not attempt model binding the out parameters else if (!parameterInfo.IsOut) { bool validateRequest; IValueProvider customValueProvider = GetCustomValueProvider(modelBindingExecutionContext, parameterInfo, ref modelName, out validateRequest); //When we are evaluating the parameter at the time of page load, we do not want to populate the actual ModelState //because there will be another evaluation at data-binding causing duplicate errors if model validation fails. ModelStateDictionary modelState = isPageLoadComplete ? new ModelStateDictionary() : _owner.DataControl.Page.ModelState; ModelBindingContext bindingContext = new ModelBindingContext() { ModelBinderProviders = ModelBinderProviders.Providers, ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterInfo.ParameterType), ModelState = modelState, ModelName = modelName, ValueProvider = customValueProvider, ValidateRequest = validateRequest }; //Select parameters that take custom values providers are tracked by ViewState so that //we can detect any changes from previous page request and mark the data bound control for data binding if necessary. if (dataSourceOperation == DataSourceOperation.Select && customValueProvider != null && parameterInfo.ParameterType.IsSerializable) { if (!SelectParameters.ContainsKey(parameterInfo.Name)) { SelectParameters.Add(parameterInfo.Name, new MethodParameterValue()); } if (binder.BindModel(modelBindingExecutionContext, bindingContext)) { value = bindingContext.Model; } SelectParameters[parameterInfo.Name].UpdateValue(value); } else { if (isPageLoadComplete) { Debug.Assert(dataSourceOperation == DataSourceOperation.Select, "Only Select Operation should have been done immediately after page load"); //When this method is called as part of Page's LoadComplete event handler we do not have values in defaultValueProvider //(i.e., values from DataBoundControl), so we need not evaluate the parameters values. continue; } if (customValueProvider == null) { bindingContext.ValueProvider = dataBoundControlValueProvider; } if (binder.BindModel(modelBindingExecutionContext, bindingContext)) { value = bindingContext.Model; } } // We set the CancellationToken after EvaluateMethodParameters(). // We don't want to set a null value to a CancellationToken variable. if (parameterInfo == lastParameter && typeof(CancellationToken) == parameterInfo.ParameterType && value == null) { value = CancellationToken.None; } if (!isPageLoadComplete) { ValidateParameterValue(parameterInfo, value, actionMethod); } } modelDataSourceMethod.Parameters.Add(parameterInfo.Name, value); } if (previousDataControl != null) { modelBindingExecutionContext.PublishService<Control>(previousDataControl); } }
public LinqDataSourceContextEventArgs(DataSourceOperation operation) { _operation = operation; }
public LinqDataSourceContextEventArgs() { _operation = DataSourceOperation.Select; }
internal ObjectDataSourceMethod(DataSourceOperation operation, Type type, MethodInfo methodInfo, OrderedDictionary parameters) { Operation = operation; Type = type; Parameters = parameters; MethodInfo = methodInfo; }
/// <devdoc> /// Resolves a method based on a type and the name of the method. Overload resolution is /// performed primarily based on the names of parameters passed in the two dictionary /// parameters. Conflict resolution is done based on a rating scale of confidence levels /// (see comments in this method). /// The return value is the MethodInfo that was found along with an array of parameter /// values to be passed in for the invocation. /// </devdoc> private ObjectDataSourceMethod GetResolvedMethodData(Type type, string methodName, IDictionary allParameters, DataSourceOperation operation) { Debug.Assert(allParameters != null, "The 'allParameters' dictionary should never be null"); // Since there is no method type for SelectCount, we special case it bool isSelectCount = (operation == DataSourceOperation.SelectCount); DataObjectMethodType methodType = DataObjectMethodType.Select; if (!isSelectCount) { methodType = GetMethodTypeFromOperation(operation); } // Get a list of all the overloads of the requested method MethodInfo[] methods = type.GetMethods( BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy); MethodInfo matchedMethod = null; ParameterInfo[] matchedMethodParameters = null; // Indicates how confident we are that a method overload is a good match // -1 - indicates no confidence - no appropriate methods have been found at all // 0 - indicates low confidence - only parameter names match // 1 - indicates medium confidence - parameter names match, method is DataObjectMethod // 2 - indicates high confidence - parameter names match, method is DataObjectMethod, is default method int highestConfidence = -1; bool confidenceConflict = false; // Indicates that there is more than one method at the current highest confidence level int allParameterCount = allParameters.Count; foreach (MethodInfo mi in methods) { if (String.Equals(methodName, mi.Name, StringComparison.OrdinalIgnoreCase)) { if (mi.IsGenericMethodDefinition) { // We do not support binding to generic methods, e.g. public void DoSomething<T>(T t) continue; } ParameterInfo[] methodParameters = mi.GetParameters(); int methodParametersCount = methodParameters.Length; // We are not using DataObject. There is either a Select operation, or it is an // Update/Insert/Delete operation that does not use DataObjects. // First check if the parameter counts match if (methodParametersCount != allParameterCount) { continue; } // Check if all the parameter names match bool parameterMismatch = false; foreach (ParameterInfo pi in methodParameters) { if (!allParameters.Contains(pi.Name)) { parameterMismatch = true; break; } } if (parameterMismatch) { continue; } int confidence = 0; // See comment above regarding confidence if (!isSelectCount) { DataObjectMethodAttribute attr = Attribute.GetCustomAttribute(mi, typeof(DataObjectMethodAttribute), true) as DataObjectMethodAttribute; if (attr != null) { if (attr.MethodType == methodType) { if (attr.IsDefault) { // Method is decorated and is default confidence = 2; } else { // Method is decorated but not default confidence = 1; } } } } // If we found another method if (confidence == highestConfidence) { confidenceConflict = true; } else { // If method looks like it's the best match so far, store it if (confidence > highestConfidence) { highestConfidence = confidence; confidenceConflict = false; matchedMethod = mi; matchedMethodParameters = methodParameters; } } } } if (confidenceConflict) { // There was more than one method that looked like a good match, but none had // a higher confidence level than the others, so we fail. See comment above // regarding confidence levels. throw new InvalidOperationException(SR.GetString(SR.ObjectDataSourceView_MultipleOverloads, _owner.ID)); } if (matchedMethod == null) { if (allParameterCount == 0) { throw new InvalidOperationException(SR.GetString(SR.ObjectDataSourceView_MethodNotFoundNoParams, _owner.ID, methodName)); } else { string[] paramNames = new string[allParameterCount]; allParameters.Keys.CopyTo(paramNames, 0); string paramString = String.Join(", ", paramNames); throw new InvalidOperationException(SR.GetString(SR.ObjectDataSourceView_MethodNotFoundWithParams, _owner.ID, methodName, paramString)); } } Debug.Assert(matchedMethodParameters != null, "Method parameters should not be null if a method was found"); OrderedDictionary parameters = null; // Create the actual parameter list to be passed to the method int methodParameterCount = matchedMethodParameters.Length; if (methodParameterCount > 0) { parameters = new OrderedDictionary(methodParameterCount, StringComparer.OrdinalIgnoreCase); bool convertNullToDBNull = ConvertNullToDBNull; for (int i = 0; i < matchedMethodParameters.Length; i++) { ParameterInfo methodParameter = matchedMethodParameters[i]; string paramName = methodParameter.Name; // Check if the required parameter exists in the input parameters Debug.Assert(allParameters.Contains(paramName)); object parameterValue = allParameters[paramName]; if (convertNullToDBNull && (parameterValue == null)) { parameterValue = DBNull.Value; } else { parameterValue = BuildObjectValue(parameterValue, methodParameter.ParameterType, paramName, ParsingCulture); } parameters.Add(paramName, parameterValue); } } return new ObjectDataSourceMethod(operation, type, matchedMethod, parameters); }
private ObjectDataSourceMethod GetResolvedMethodData(Type type, string methodName, Type dataObjectType, object oldDataObject, object newDataObject, DataSourceOperation operation) { Debug.Assert(dataObjectType != null, "This overload of GetResolvedMethodData should only be called when using a DataObject"); Debug.Assert(oldDataObject != null || newDataObject != null, "Did not expect both oldDataObject and newDataObject to be null"); // Get a list of all the overloads of the requested method MethodInfo[] methods = type.GetMethods( BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy); MethodInfo matchedMethod = null; ParameterInfo[] matchedMethodParameters = null; int requiredParameterCount; if (oldDataObject == null) { requiredParameterCount = 1; } else { if (newDataObject == null) { requiredParameterCount = 1; } else { requiredParameterCount = 2; } } foreach (MethodInfo mi in methods) { if (String.Equals(methodName, mi.Name, StringComparison.OrdinalIgnoreCase)) { if (mi.IsGenericMethodDefinition) { // We do not support binding to generic methods, e.g. public void DoSomething<T>(T t) continue; } ParameterInfo[] methodParameters = mi.GetParameters(); int methodParametersCount = methodParameters.Length; if (methodParametersCount == requiredParameterCount) { if (requiredParameterCount == 1 && methodParameters[0].ParameterType == dataObjectType) { // Only one parameter, of proper type // This is only valid for insert, delete, and non-optimistic update matchedMethod = mi; matchedMethodParameters = methodParameters; break; } if (requiredParameterCount == 2 && methodParameters[0].ParameterType == dataObjectType && methodParameters[1].ParameterType == dataObjectType) { // Two parameters of proper type in Update // This is only valid for optimistic update matchedMethod = mi; matchedMethodParameters = methodParameters; break; } } } } if (matchedMethod == null) { throw new InvalidOperationException(SR.GetString(SR.ObjectDataSourceView_MethodNotFoundForDataObject, _owner.ID, methodName, dataObjectType.FullName)); } Debug.Assert(matchedMethodParameters != null, "Method parameters should not be null if a method was found"); // Set up parameter array for method call OrderedDictionary parameters = new OrderedDictionary(2, StringComparer.OrdinalIgnoreCase); if (oldDataObject == null) { parameters.Add(matchedMethodParameters[0].Name, newDataObject); } else { if (newDataObject == null) { parameters.Add(matchedMethodParameters[0].Name, oldDataObject); } else { // We know that we matched on 2 objects for a optimistic update. // Match the parameters based on the format string so we know which one is the old // object and which is the new, then pass objects into the method in the correct order. string param0Name = matchedMethodParameters[0].Name; string param1Name = matchedMethodParameters[1].Name; string formattedParamName = String.Format(CultureInfo.InvariantCulture, OldValuesParameterFormatString, param0Name); if (String.Equals(param1Name, formattedParamName, StringComparison.OrdinalIgnoreCase)) { parameters.Add(param0Name, newDataObject); parameters.Add(param1Name, oldDataObject); } else { formattedParamName = String.Format(CultureInfo.InvariantCulture, OldValuesParameterFormatString, param1Name); if (String.Equals(param0Name, formattedParamName, StringComparison.OrdinalIgnoreCase)) { parameters.Add(param0Name, oldDataObject); parameters.Add(param1Name, newDataObject); } else { throw new InvalidOperationException(SR.GetString(SR.ObjectDataSourceView_NoOldValuesParams, _owner.ID)); } } } } // The parameters collection is always readonly in this case since we // do not want the user adding/removing the known objects. return new ObjectDataSourceMethod(operation, type, matchedMethod, parameters.AsReadOnly()); }
/// <devdoc> /// Returns true if the two parameters represent the same type of operation. /// </devdoc> private static DataObjectMethodType GetMethodTypeFromOperation(DataSourceOperation operation) { switch (operation) { case DataSourceOperation.Delete: return DataObjectMethodType.Delete; case DataSourceOperation.Insert: return DataObjectMethodType.Insert; case DataSourceOperation.Select: return DataObjectMethodType.Select; case DataSourceOperation.Update: return DataObjectMethodType.Update; } throw new ArgumentOutOfRangeException("operation"); }
private int ExecuteDbCommand(DbCommand command, DataSourceOperation operation) { int affectedRows = 0; bool flag = false; try { if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } affectedRows = command.ExecuteNonQuery(); if (affectedRows > 0) { this.OnDataSourceViewChanged(EventArgs.Empty); DataSourceCache cache = this._owner.Cache; if ((cache != null) && cache.Enabled) { this._owner.InvalidateCacheEntry(); } } flag = true; SqlDataSourceStatusEventArgs e = new SqlDataSourceStatusEventArgs(command, affectedRows, null); switch (operation) { case DataSourceOperation.Delete: this.OnDeleted(e); return affectedRows; case DataSourceOperation.Insert: this.OnInserted(e); return affectedRows; case DataSourceOperation.Select: return affectedRows; case DataSourceOperation.Update: this.OnUpdated(e); return affectedRows; } return affectedRows; } catch (Exception exception) { bool flag2; if (!flag) { SqlDataSourceStatusEventArgs args2 = new SqlDataSourceStatusEventArgs(command, affectedRows, exception); switch (operation) { case DataSourceOperation.Delete: this.OnDeleted(args2); break; case DataSourceOperation.Insert: this.OnInserted(args2); break; case DataSourceOperation.Update: this.OnUpdated(args2); break; } if (!args2.ExceptionHandled) { throw; } return affectedRows; } exception = this.BuildCustomException(exception, operation, command, out flag2); if (flag2) { throw exception; } throw; } finally { if (command.Connection.State == ConnectionState.Open) { command.Connection.Close(); } } return affectedRows; }
/// <summary> /// Evaluates the method parameters using model binding. /// </summary> /// <param name="dataSourceOperation">The datasource operation for which parameters are being evaluated.</param> /// <param name="modelDataSourceMethod">The ModelDataSourceMethod object for which the Parameter collection is being evaluated. The MethodInfo property should already be set on this object.</param> /// <param name="controlValues">The values from the data bound control.</param> protected virtual void EvaluateMethodParameters(DataSourceOperation dataSourceOperation, ModelDataSourceMethod modelDataSourceMethod, IDictionary controlValues) { EvaluateMethodParameters(dataSourceOperation, modelDataSourceMethod, controlValues, isPageLoadComplete: false); }
private bool EditQueryChangeCallback(object context) { SqlDataSource first = (SqlDataSource)((Pair)context).First; DataSourceOperation second = (DataSourceOperation)((Pair)context).Second; IServiceProvider site = first.Site; IDesignerHost service = (IDesignerHost)site.GetService(typeof(IDesignerHost)); SqlDataSourceDesigner sqlDataSourceDesigner = (SqlDataSourceDesigner)service.GetDesigner(first); ParameterCollection originalParameters = null; string command = string.Empty; SqlDataSourceCommandType text = SqlDataSourceCommandType.Text; switch (second) { case DataSourceOperation.Delete: originalParameters = first.DeleteParameters; command = first.DeleteCommand; text = first.DeleteCommandType; break; case DataSourceOperation.Insert: originalParameters = first.InsertParameters; command = first.InsertCommand; text = first.InsertCommandType; break; case DataSourceOperation.Select: originalParameters = first.SelectParameters; command = first.SelectCommand; text = first.SelectCommandType; break; case DataSourceOperation.Update: originalParameters = first.UpdateParameters; command = first.UpdateCommand; text = first.UpdateCommandType; break; } SqlDataSourceQueryEditorForm form = new SqlDataSourceQueryEditorForm(site, sqlDataSourceDesigner, first.ProviderName, sqlDataSourceDesigner.ConnectionString, second, text, command, originalParameters); if (UIServiceHelper.ShowDialog(site, form) != DialogResult.OK) { return(false); } PropertyDescriptor descriptor = null; switch (second) { case DataSourceOperation.Delete: descriptor = TypeDescriptor.GetProperties(first)["DeleteCommand"]; break; case DataSourceOperation.Insert: descriptor = TypeDescriptor.GetProperties(first)["InsertCommand"]; break; case DataSourceOperation.Select: descriptor = TypeDescriptor.GetProperties(first)["SelectCommand"]; break; case DataSourceOperation.Update: descriptor = TypeDescriptor.GetProperties(first)["UpdateCommand"]; break; } if (descriptor != null) { descriptor.ResetValue(first); descriptor.SetValue(first, form.Command); } return(true); }
public SqlDataSourceQueryEditorForm(IServiceProvider serviceProvider, SqlDataSourceDesigner sqlDataSourceDesigner, string providerName, string connectionString, DataSourceOperation operation, SqlDataSourceCommandType commandType, string command, IList originalParameters) : base(serviceProvider) { this._sqlDataSourceDesigner = sqlDataSourceDesigner; this.InitializeComponent(); this.InitializeUI(); if (string.IsNullOrEmpty(providerName)) { providerName = "System.Data.SqlClient"; } this._dataConnection = new DesignerDataConnection(string.Empty, providerName, connectionString); this._commandType = commandType; this._commandTextBox.Text = command; this._originalParameters = originalParameters; string str = Enum.GetName(typeof(DataSourceOperation), operation).ToUpperInvariant(); this._commandLabel.Text = System.Design.SR.GetString("SqlDataSourceQueryEditorForm_CommandLabel", new object[] { str }); ArrayList dest = new ArrayList(originalParameters.Count); sqlDataSourceDesigner.CopyList(originalParameters, dest); this._parameterEditorUserControl.AddParameters((Parameter[])dest.ToArray(typeof(Parameter))); this._commandTextBox.Select(0, 0); switch (operation) { case DataSourceOperation.Delete: this._queryBuilderMode = QueryBuilderMode.Delete; return; case DataSourceOperation.Insert: this._queryBuilderMode = QueryBuilderMode.Insert; return; case DataSourceOperation.Select: this._queryBuilderMode = QueryBuilderMode.Select; return; case DataSourceOperation.Update: this._queryBuilderMode = QueryBuilderMode.Update; return; } }
protected virtual ContextDataSourceContextData CreateContext(DataSourceOperation operation) { return(null); }
/// <summary> /// Evaluates the method parameters using model binding. /// </summary> /// <param name="dataSourceOperation">The datasource operation for which parameters are being evaluated.</param> /// <param name="modelDataSourceMethod">The ModelDataSourceMethod object for which the Parameter collection is being evaluated. The MethodInfo property should already be set on this object.</param> /// <param name="controlValues">The values from the data bound control.</param> /// <param name="isPageLoadComplete">This must be set to true only when this method is called in Page's LoadComplete event handler /// to evaluate the select method parameters that use custom value providers so that we can identify any changes /// to those and mark the data-bound control for data binding if necessary.</param> protected virtual void EvaluateMethodParameters(DataSourceOperation dataSourceOperation, ModelDataSourceMethod modelDataSourceMethod, IDictionary controlValues, bool isPageLoadComplete) { Debug.Assert(_owner.DataControl.Page != null); Debug.Assert(_owner.DataControl.TemplateControl != null); MethodInfo actionMethod = modelDataSourceMethod.MethodInfo; IModelBinder binder = ModelBinders.Binders.DefaultBinder; IValueProvider dataBoundControlValueProvider = GetValueProviderFromDictionary(controlValues); ModelBindingExecutionContext modelBindingExecutionContext = _owner.DataControl.Page.ModelBindingExecutionContext; //This is used by ControlValueProvider later. modelBindingExecutionContext.PublishService <Control>(_owner.DataControl); //This is done for the TryUpdateModel to work inside a Data Method. if (dataSourceOperation != DataSourceOperation.Select) { _owner.DataControl.Page.SetActiveValueProvider(dataBoundControlValueProvider); } foreach (ParameterInfo parameterInfo in actionMethod.GetParameters()) { object value = null; string modelName = parameterInfo.Name; if (parameterInfo.ParameterType == typeof(ModelMethodContext)) { //ModelMethodContext is a special parameter we pass in for enabling developer to call //TryUpdateModel when Select/Update/Delete/InsertMethods are on a custom class. value = new ModelMethodContext(_owner.DataControl.Page); } //Do not attempt model binding the out parameters else if (!parameterInfo.IsOut) { bool validateRequest; IValueProvider customValueProvider = GetCustomValueProvider(modelBindingExecutionContext, parameterInfo, ref modelName, out validateRequest); //When we are evaluating the parameter at the time of page load, we do not want to populate the actual ModelState //because there will be another evaluation at data-binding causing duplicate errors if model validation fails. ModelStateDictionary modelState = isPageLoadComplete ? new ModelStateDictionary() : _owner.DataControl.Page.ModelState; ModelBindingContext bindingContext = new ModelBindingContext() { ModelBinderProviders = ModelBinderProviders.Providers, ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, parameterInfo.ParameterType), ModelState = modelState, ModelName = modelName, ValueProvider = customValueProvider, ValidateRequest = validateRequest }; //Select parameters that take custom values providers are tracked by ViewState so that //we can detect any changes from previous page request and mark the data bound control for data binding if necessary. if (dataSourceOperation == DataSourceOperation.Select && customValueProvider != null && parameterInfo.ParameterType.IsSerializable) { if (!SelectParameters.ContainsKey(parameterInfo.Name)) { SelectParameters.Add(parameterInfo.Name, new MethodParameterValue()); } if (binder.BindModel(modelBindingExecutionContext, bindingContext)) { value = bindingContext.Model; } SelectParameters[parameterInfo.Name].UpdateValue(value); } else { if (isPageLoadComplete) { Debug.Assert(dataSourceOperation == DataSourceOperation.Select, "Only Select Operation should have been done immediately after page load"); //When this method is called as part of Page's LoadComplete event handler we do not have values in defaultValueProvider //(i.e., values from DataBoundControl), so we need not evaluate the parameters values. continue; } if (customValueProvider == null) { bindingContext.ValueProvider = dataBoundControlValueProvider; } if (binder.BindModel(modelBindingExecutionContext, bindingContext)) { value = bindingContext.Model; } } if (!isPageLoadComplete) { ValidateParameterValue(parameterInfo, value, actionMethod); } } modelDataSourceMethod.Parameters.Add(parameterInfo.Name, value); } }
protected override ContextDataSourceContextData CreateContext(DataSourceOperation operation) { if (operation == DataSourceOperation.Select) { return CreateContextAndTableForSelect(); } return CreateContextAndTableForEdit(operation); }
/// <devdoc> /// Executes a DbCommand and returns the number of rows affected. /// </devdoc> private int ExecuteDbCommand(DbCommand command, DataSourceOperation operation) { int rowsAffected = 0; bool eventRaised = false; try { if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } rowsAffected = command.ExecuteNonQuery(); if (rowsAffected > 0) { OnDataSourceViewChanged(EventArgs.Empty); DataSourceCache cache = _owner.Cache; if ((cache != null) && (cache.Enabled)) { _owner.InvalidateCacheEntry(); } } // Raise appropriate event eventRaised = true; SqlDataSourceStatusEventArgs eventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, null); switch (operation) { case DataSourceOperation.Delete: OnDeleted(eventArgs); break; case DataSourceOperation.Insert: OnInserted(eventArgs); break; case DataSourceOperation.Update: OnUpdated(eventArgs); break; } } catch (Exception ex) { if (!eventRaised) { // Raise appropriate event SqlDataSourceStatusEventArgs eventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, ex); switch (operation) { case DataSourceOperation.Delete: OnDeleted(eventArgs); break; case DataSourceOperation.Insert: OnInserted(eventArgs); break; case DataSourceOperation.Update: OnUpdated(eventArgs); break; } if (!eventArgs.ExceptionHandled) { throw; } } else { bool isCustomException; ex = BuildCustomException(ex, operation, command, out isCustomException); if (isCustomException) { throw ex; } else { throw; } } } finally { if (command.Connection.State == ConnectionState.Open) { command.Connection.Close(); } } return rowsAffected; }
private ContextDataSourceContextData CreateContextAndTable(DataSourceOperation operation) { ContextDataSourceContextData contextData = null; bool eventFired = false; try { LinqDataSourceContextEventArgs contextEventArgs = new LinqDataSourceContextEventArgs(operation); OnContextCreating(contextEventArgs); contextData = new ContextDataSourceContextData(contextEventArgs.ObjectInstance); Type contextType = null; MemberInfo tableMemberInfo = null; if (contextData.Context == null) { // construct the context unless accessing a static table for Select. contextType = ContextType; tableMemberInfo = GetTableMemberInfo(contextType); if (tableMemberInfo != null) { if (MemberIsStatic(tableMemberInfo)) { if (operation != DataSourceOperation.Select) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_TableCannotBeStatic, TableName, contextType.Name, _owner.ID)); } } else { contextData.Context = CreateContext(contextType); _isNewContext = true; } } } else { // use the manually constructed context. tableMemberInfo = GetTableMemberInfo(contextData.Context.GetType()); } // fetch the table from the context. if (tableMemberInfo != null) { FieldInfo field = tableMemberInfo as FieldInfo; if (field != null) { contextData.EntitySet = field.GetValue(contextData.Context); } PropertyInfo property = tableMemberInfo as PropertyInfo; if (property != null) { contextData.EntitySet = property.GetValue(contextData.Context, null); } } if (contextData.EntitySet == null) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_TableNameNotFound, TableName, contextType.Name, _owner.ID)); } } catch (Exception e) { eventFired = true; LinqDataSourceStatusEventArgs createdEventArgs = new LinqDataSourceStatusEventArgs(e); OnContextCreated(createdEventArgs); OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.ContextCreate)); // CreateContextAndTable will return null if this exception is handled. if (!createdEventArgs.ExceptionHandled) { throw; } } finally { if (!eventFired) { // contextData can be null if exception thrown from ContextCreating handler. object context = (contextData == null) ? null : contextData.Context; LinqDataSourceStatusEventArgs createdEventArgs = new LinqDataSourceStatusEventArgs(context); OnContextCreated(createdEventArgs); } } return(contextData); }
protected override void HandleValidationErrors(IDictionary <string, Exception> errors, DataSourceOperation operation) { LinqDataSourceValidationException exception = new LinqDataSourceValidationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_ValidationFailed, EntityType, errors.Values.First().Message), errors); bool exceptionHandled = false; switch (operation) { case DataSourceOperation.Delete: LinqDataSourceDeleteEventArgs deleteEventArgs = new LinqDataSourceDeleteEventArgs(exception); OnDeleting(deleteEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Delete)); exceptionHandled = deleteEventArgs.ExceptionHandled; break; case DataSourceOperation.Insert: LinqDataSourceInsertEventArgs insertEventArgs = new LinqDataSourceInsertEventArgs(exception); OnInserting(insertEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Insert)); exceptionHandled = insertEventArgs.ExceptionHandled; break; case DataSourceOperation.Update: // allow user to handle conversion or dlinq property validation exceptions. LinqDataSourceUpdateEventArgs updateEventArgs = new LinqDataSourceUpdateEventArgs(exception); OnUpdating(updateEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Update)); exceptionHandled = updateEventArgs.ExceptionHandled; break; } if (!exceptionHandled) { throw exception; } }
internal ObjectDataSourceMethod(DataSourceOperation operation, System.Type type, System.Reflection.MethodInfo methodInfo, OrderedDictionary parameters) { this.Operation = operation; this.Type = type; this.Parameters = parameters; this.MethodInfo = methodInfo; }
protected override void HandleValidationErrors(IDictionary<string, Exception> errors, DataSourceOperation operation) { }
protected abstract void HandleValidationErrors(IDictionary <string, Exception> errors, DataSourceOperation operation);
private ContextDataSourceContextData CreateContextAndTable(DataSourceOperation operation) { ContextDataSourceContextData contextData = null; bool eventFired = false; try { LinqDataSourceContextEventArgs contextEventArgs = new LinqDataSourceContextEventArgs(operation); OnContextCreating(contextEventArgs); contextData = new ContextDataSourceContextData(contextEventArgs.ObjectInstance); Type contextType = null; MemberInfo tableMemberInfo = null; if (contextData.Context == null) { // construct the context unless accessing a static table for Select. contextType = ContextType; tableMemberInfo = GetTableMemberInfo(contextType); if (tableMemberInfo != null) { if (MemberIsStatic(tableMemberInfo)) { if (operation != DataSourceOperation.Select) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_TableCannotBeStatic, TableName, contextType.Name, _owner.ID)); } } else { contextData.Context = CreateContext(contextType); _isNewContext = true; } } } else { // use the manually constructed context. tableMemberInfo = GetTableMemberInfo(contextData.Context.GetType()); } // fetch the table from the context. if (tableMemberInfo != null) { FieldInfo field = tableMemberInfo as FieldInfo; if (field != null) { contextData.EntitySet = field.GetValue(contextData.Context); } PropertyInfo property = tableMemberInfo as PropertyInfo; if (property != null) { contextData.EntitySet = property.GetValue(contextData.Context, null); } } if (contextData.EntitySet == null) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_TableNameNotFound, TableName, contextType.Name, _owner.ID)); } } catch (Exception e) { eventFired = true; LinqDataSourceStatusEventArgs createdEventArgs = new LinqDataSourceStatusEventArgs(e); OnContextCreated(createdEventArgs); OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.ContextCreate)); // CreateContextAndTable will return null if this exception is handled. if (!createdEventArgs.ExceptionHandled) { throw; } } finally { if (!eventFired) { // contextData can be null if exception thrown from ContextCreating handler. object context = (contextData == null) ? null : contextData.Context; LinqDataSourceStatusEventArgs createdEventArgs = new LinqDataSourceStatusEventArgs(context); OnContextCreated(createdEventArgs); } } return contextData; }
private Exception BuildCustomException(Exception ex, DataSourceOperation operation, DbCommand command, out bool isCustomException) { SqlException exception = ex as SqlException; if ((exception != null) && ((exception.Number == 0x89) || (exception.Number == 0xc9))) { string str; if (command.Parameters.Count > 0) { StringBuilder builder = new StringBuilder(); bool flag = true; foreach (DbParameter parameter in command.Parameters) { if (!flag) { builder.Append(", "); } builder.Append(parameter.ParameterName); flag = false; } str = builder.ToString(); } else { str = System.Web.SR.GetString("SqlDataSourceView_NoParameters"); } isCustomException = true; return new InvalidOperationException(System.Web.SR.GetString("SqlDataSourceView_MissingParameters", new object[] { operation, this._owner.ID, str })); } isCustomException = false; return ex; }
private ContextDataSourceContextData CreateContextAndTableForEdit(DataSourceOperation operation) { ContextDataSourceContextData contextData = CreateContextAndTable(operation); // context data may be null or incomplete if an exception was handled if (contextData != null) { if (contextData.Context == null) { return null; } if (contextData.EntitySet == null) { DisposeContext(contextData.Context); return null; } ValidateContextType(contextData.Context.GetType(), false); ValidateTableType(contextData.EntitySet.GetType(), false); } return contextData; }
protected override void HandleValidationErrors(IDictionary<string, Exception> errors, DataSourceOperation operation) { LinqDataSourceValidationException exception = new LinqDataSourceValidationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_ValidationFailed, EntityType, errors.Values.First().Message), errors); bool exceptionHandled = false; switch (operation) { case DataSourceOperation.Delete: LinqDataSourceDeleteEventArgs deleteEventArgs = new LinqDataSourceDeleteEventArgs(exception); OnDeleting(deleteEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Delete)); exceptionHandled = deleteEventArgs.ExceptionHandled; break; case DataSourceOperation.Insert: LinqDataSourceInsertEventArgs insertEventArgs = new LinqDataSourceInsertEventArgs(exception); OnInserting(insertEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Insert)); exceptionHandled = insertEventArgs.ExceptionHandled; break; case DataSourceOperation.Update: // allow user to handle conversion or dlinq property validation exceptions. LinqDataSourceUpdateEventArgs updateEventArgs = new LinqDataSourceUpdateEventArgs(exception); OnUpdating(updateEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Update)); exceptionHandled = updateEventArgs.ExceptionHandled; break; } if (!exceptionHandled) { throw exception; } }
public LinqDataSourceContextEventArgs (DataSourceOperation operation) { Operation = operation; }
protected virtual ContextDataSourceContextData CreateContext(DataSourceOperation operation) { return null; }