Пример #1
0
 /// <summary>
 /// Creates an instance of the object.
 /// </summary>
 /// <param name="message">Text describing the exception.</param>
 /// <param name="ex">Inner exception.</param>
 /// <param name="result">The data portal result object.</param>
 public DataPortalException(
   string message, Exception ex, DataPortalResult result)
   : base(message, ex)
 {
   _innerStackTrace = ex.StackTrace;
   _result = result;
 }
Пример #2
0
 /// <summary>
 /// Creates an instance of the object for serialization.
 /// </summary>
 /// <param name="info">Serialiation info object.</param>
 /// <param name="context">Serialization context object.</param>
 protected DataPortalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
   : base(info, context)
 {
   _result = (DataPortalResult)info.GetValue(
     "_result", typeof(DataPortalResult));
   _innerStackTrace = info.GetString("_innerStackTrace");
 }
Пример #3
0
        internal async Task DoDeleteAsync(Type objectType, object criteria, bool isSync)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            try
            {
                DataPortal.OnDataPortalInitInvoke(null);

                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.DeleteObject, objectType, Server.DataPortal.GetCriteriaArray(criteria)))
                {
                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                            "delete",
                                                                            objectType.Name));
                }

                var method = Reflection.ServiceProviderMethodCaller.FindDataPortalMethod <DeleteAttribute>(objectType, Server.DataPortal.GetCriteriaArray(criteria), false);
                var proxy  = GetDataPortalProxy(objectType, method);

                dpContext = new Server.DataPortalContext(GetPrincipal(), proxy.IsServerRemote);

                DataPortal.OnDataPortalInvoke(new DataPortalEventArgs(dpContext, objectType, criteria, DataPortalOperations.Delete));

                try
                {
                    result = await proxy.Delete(objectType, criteria, dpContext, isSync);
                }
                catch (AggregateException ex)
                {
                    if (ex.InnerExceptions.Count > 0)
                    {
                        var dpe = ex.InnerExceptions[0] as Server.DataPortalException;
                        if (dpe != null)
                        {
                            HandleDeleteDataPortalException(dpe, isSync, proxy);
                        }
                    }
                    throw new DataPortalException(
                              string.Format("DataPortal.Delete {0}", Resources.Failed),
                              ex, null);
                }
                catch (Server.DataPortalException ex)
                {
                    HandleDeleteDataPortalException(ex, isSync, proxy);
                }

                GlobalContext = result.GlobalContext;
                if (proxy.IsServerRemote && isSync)
                {
                    ApplicationContext.ContextManager.SetGlobalContext(result.GlobalContext);
                }

                DataPortal.OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, criteria, DataPortalOperations.Delete));
            }
            catch (Exception ex)
            {
                DataPortal.OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, criteria, DataPortalOperations.Delete, ex));
                throw;
            }
        }
Пример #4
0
        /// <summary>
        /// Called by a factory method in a business class to create
        /// a new object, which is loaded with default
        /// values from the database.
        /// </summary>
        /// <param name="objectType">Type of business object to create.</param>
        /// <param name="criteria">Object-specific criteria.</param>
        /// <returns>A new object, populated with default values.</returns>
        public static object Create(Type objectType, object criteria)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            try
            {
                OnDataPortalInitInvoke(null);

                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.CreateObject, objectType))
                {
                    throw new System.Security.SecurityException(string.Format(
                                                                    Resources.UserNotAuthorizedException,
                                                                    "create",
                                                                    objectType.Name));
                }

                var method = Server.DataPortalMethodCache.GetCreateMethod(objectType, criteria);

                DataPortalClient.IDataPortalProxy proxy;
                proxy = GetDataPortalProxy(objectType, method.RunLocal);

                dpContext =
                    new Csla.Server.DataPortalContext(GetPrincipal(), proxy.IsServerRemote);

                OnDataPortalInvoke(new DataPortalEventArgs(dpContext, objectType, DataPortalOperations.Create));

                try
                {
                    result = proxy.Create(objectType, criteria, dpContext);
                }
                catch (Server.DataPortalException ex)
                {
                    result = ex.Result;
                    if (proxy.IsServerRemote)
                    {
                        ApplicationContext.ContextManager.SetGlobalContext(result.GlobalContext);
                    }
                    throw new DataPortalException(
                              string.Format("DataPortal.Create {0} ({1})", Resources.Failed, ex.InnerException.InnerException),
                              ex.InnerException, result.ReturnObject);
                }

                if (proxy.IsServerRemote)
                {
                    ApplicationContext.ContextManager.SetGlobalContext(result.GlobalContext);
                }

                OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, DataPortalOperations.Create));
            }
            catch (Exception ex)
            {
                OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, DataPortalOperations.Create, ex));
                throw;
            }
            return(result.ReturnObject);
        }
Пример #5
0
        private async Task <object> DoCreateAsync(Type objectType, object criteria, bool isSync)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            try
            {
                if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.CreateObject, objectType, Server.DataPortal.GetCriteriaArray(criteria)))
                {
                    throw new Csla.Security.SecurityException(string.Format(
                                                                  Resources.UserNotAuthorizedException,
                                                                  "create",
                                                                  objectType.Name));
                }
                Reflection.ServiceProviderMethodInfo method;
                if (criteria is Server.EmptyCriteria)
                {
                    method = ServiceProviderMethodCaller.FindDataPortalMethod <CreateAttribute>(objectType, null, false);
                }
                else
                {
                    method = ServiceProviderMethodCaller.FindDataPortalMethod <CreateAttribute>(objectType, Server.DataPortal.GetCriteriaArray(criteria), false);
                }
                var proxy = GetDataPortalProxy(method);

                dpContext =
                    new Csla.Server.DataPortalContext(ApplicationContext, GetPrincipal(), proxy.IsServerRemote);

                try
                {
                    result = await proxy.Create(objectType, criteria, dpContext, isSync);
                }
                catch (AggregateException ex)
                {
                    if (ex.InnerExceptions.Count > 0)
                    {
                        if (ex.InnerExceptions[0] is Server.DataPortalException dpe)
                        {
                            HandleCreateDataPortalException(dpe, isSync, proxy);
                        }
                    }
                    throw new DataPortalException(
                              string.Format("DataPortal.Create {0}", Resources.Failed),
                              ex, null);
                }
                catch (Server.DataPortalException ex)
                {
                    HandleCreateDataPortalException(ex, isSync, proxy);
                }
            }
            catch
            {
                throw;
            }
            return(result.ReturnObject);
        }
Пример #6
0
 /// <summary>
 /// Get an existing business object.
 /// </summary>
 /// <param name="objectTypeName">Type of business object to retrieve.</param>
 /// <param name="criteriaData">Criteria object describing business object.</param>
 /// <param name="contextData">
 /// Server.DataPortalContext object passed to the server.
 /// </param>
 public async Task<byte[]> Fetch(string objectTypeName, byte[] criteriaData, byte[] contextData)
 {
   DataPortalResult result;
   try
   {
     var objectType = Csla.Reflection.MethodCaller.GetType(objectTypeName);
     var criteria = Csla.Serialization.Mobile.MobileFormatter.Deserialize(criteriaData);
     var context = (DataPortalContext)Csla.Serialization.Mobile.MobileFormatter.Deserialize(contextData);
     var portal = new Csla.Server.DataPortal();
     result = await portal.Fetch(objectType, criteria, context, false);
   }
   catch (Exception ex)
   {
     result = new DataPortalResult(null, ex, null);
   }
   var response = GetDataPortalResult(result);
   var resultData = Csla.Serialization.Mobile.MobileFormatter.Serialize(response);
   return resultData;
 }
Пример #7
0
 /// <summary>
 /// Called by the client-side DataPortal to create a
 /// new business object.
 /// </summary>
 /// <param name="objectType">Type of business object to create.</param>
 /// <param name="criteria">Criteria object describing business object.</param>
 /// <param name="context">Server.DataPortalContext object passed to the server.</param>
 /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
 public async Task<DataPortalResult> Create(Type objectType, object criteria, DataPortalContext context, bool isSync)
 {
   DataPortalResult result = null;
   if (isSync)
     throw new NotSupportedException("isSync == true");
   try
   {
     if (!(criteria is IMobileObject))
       criteria = new PrimitiveCriteria(criteria);
     var contextData = Csla.Serialization.Mobile.MobileFormatter.Serialize(context);
     var criteriaData = Csla.Serialization.Mobile.MobileFormatter.Serialize(criteria);
     var portal = new BrokeredHost();
     var objectTypeName = objectType.AssemblyQualifiedName;
     var resultData = await portal.Create(objectTypeName, criteriaData, contextData);
     var response = (Csla.Server.Hosts.HttpChannel.HttpResponse)Csla.Serialization.Mobile.MobileFormatter.Deserialize(resultData.ToArray());
     var globalContext = (Csla.Core.ContextDictionary)Csla.Serialization.Mobile.MobileFormatter.Deserialize(response.GlobalContext);
     if (response != null && response.ErrorData == null)
     {
       var obj = MobileFormatter.Deserialize(response.ObjectData);
       result = new DataPortalResult(obj, null, globalContext);
     }
     else if (response != null && response.ErrorData != null)
     {
       var ex = new DataPortalException(response.ErrorData);
       result = new DataPortalResult(null, ex, globalContext);
     }
     else
     {
       throw new DataPortalException("null response", null);
     }
   }
   catch (Exception ex)
   {
     result = new DataPortalResult(null, ex, null);
   }
   if (result.Error != null)
     throw result.Error;
   return result;
 }
Пример #8
0
 /// <summary>
 /// Called by the client-side DataPortal to update a
 /// business object.
 /// </summary>
 /// <param name="obj">Business object to update.</param>
 /// <param name="context">Server.DataPortalContext object passed to the server.</param>
 /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
 public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync)
 {
   DataPortalResult result = null;
   if (isSync)
     throw new NotSupportedException("isSync == true");
   try
   {
     var contextData = Csla.Serialization.Mobile.MobileFormatter.Serialize(context);
     var objectData = Csla.Serialization.Mobile.MobileFormatter.Serialize(obj);
     var portal = new BrokeredHost();
     var resultData = await portal.Update(objectData, contextData);
     var response = (Csla.Server.Hosts.HttpChannel.HttpResponse)Csla.Serialization.Mobile.MobileFormatter.Deserialize(resultData.ToArray());
     var globalContext = (Csla.Core.ContextDictionary)Csla.Serialization.Mobile.MobileFormatter.Deserialize(response.GlobalContext);
     if (response != null && response.ErrorData == null)
     {
       obj = MobileFormatter.Deserialize(response.ObjectData);
       result = new DataPortalResult(obj, null, globalContext);
     }
     else if (response != null && response.ErrorData != null)
     {
       var ex = new DataPortalException(response.ErrorData);
       result = new DataPortalResult(null, ex, globalContext);
     }
     else
     {
       throw new DataPortalException("null response", null);
     }
   }
   catch (Exception ex)
   {
     result = new DataPortalResult(null, ex, null);
   }
   return result;
 }
Пример #9
0
        public void SetSystemOptions()
        {
            var soi = Mock.Create<SystemOptionsInfo>();

            Mock.Arrange(() => systemOptions.GetSystemOptions(Arg.IsAny<EventHandler<DataPortalResult<SystemOptionsRetriever>>>()))
                .DoInstead<EventHandler<DataPortalResult<SystemOptionsRetriever>>>(
                    callback =>
                        {
                            var result = new DataPortalResult<SystemOptionsRetriever>(new SystemOptionsRetriever { SystemOptions = soi }, null, null);
                            callback(null, result);
                        });
        }
Пример #10
0
    /// <summary>
    /// Called by <see cref="DataPortal" /> to delete a
    /// business object.
    /// </summary>
    /// <param name="objectType">Type of business object to create.</param>
    /// <param name="criteria">Criteria object describing business object.</param>
    /// <param name="context">
    /// <see cref="Server.DataPortalContext" /> object passed to the server.
    /// </param>
    /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
    public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync)
#pragma warning restore 1998
    {
      DataPortalResult result = null;
      try
      {
        if (isSync)
          throw new NotSupportedException("isSync == true");
        var client = GetClient();
        if (this.Timeout > 0)
          client.Timeout = TimeSpan.FromMilliseconds(this.Timeout);
        var request = GetBaseCriteriaRequest();
        request.TypeName = AssemblyNameTranslator.GetAssemblyQualifiedName(objectType.AssemblyQualifiedName);
        if (!(criteria is IMobileObject))
        {
          criteria = new PrimitiveCriteria(criteria);
        }
        request.CriteriaData = MobileFormatter.Serialize(criteria);
        request = ConvertRequest(request);

        var serialized = MobileFormatter.Serialize(request);

        var httpRequest = new HttpRequestMessage(HttpMethod.Post, string.Format("{0}?operation=delete", DataPortalUrl));
        httpRequest.Content = new ByteArrayContent(serialized);

        var httpResponse = await client.SendAsync(httpRequest);
        httpResponse.EnsureSuccessStatusCode();
        serialized = await httpResponse.Content.ReadAsByteArrayAsync();

        var response = (Csla.Server.Hosts.HttpChannel.HttpResponse)MobileFormatter.Deserialize(serialized);
        response = ConvertResponse(response);
        var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
        if (response != null && response.ErrorData == null)
        {
          result = new DataPortalResult(null, null, globalContext);
        }
        else if (response != null && response.ErrorData != null)
        {
          var ex = new DataPortalException(response.ErrorData);
          result = new DataPortalResult(null, ex, globalContext);
        }
        else
        {
          throw new DataPortalException("null response", null);
        }
      }
      catch (Exception ex)
      {
        result = new DataPortalResult(null, ex, null);
      }
      if (result.Error != null)
        throw result.Error;
      return result;
    }
Пример #11
0
        private async Task <object> DoCreateAsync(Type objectType, object criteria, bool isSync)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            try
            {
                DataPortal.OnDataPortalInitInvoke(null);

                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.CreateObject, objectType))
                {
                    throw new Csla.Security.SecurityException(string.Format(
                                                                  Resources.UserNotAuthorizedException,
                                                                  "create",
                                                                  objectType.Name));
                }

                var method = Server.DataPortalMethodCache.GetCreateMethod(objectType, criteria);

                DataPortalClient.IDataPortalProxy proxy;
                proxy = GetDataPortalProxy(objectType, method.RunLocal);

                dpContext =
                    new Csla.Server.DataPortalContext(GetPrincipal(), proxy.IsServerRemote);

                DataPortal.OnDataPortalInvoke(new DataPortalEventArgs(dpContext, objectType, criteria, DataPortalOperations.Create));

                try
                {
                    result = await proxy.Create(objectType, criteria, dpContext, isSync);

                    GlobalContext = result.GlobalContext;
                    if (isSync && proxy.IsServerRemote)
                    {
                        ApplicationContext.ContextManager.SetGlobalContext(GlobalContext);
                    }
                }
                catch (AggregateException ex)
                {
                    if (ex.InnerExceptions.Count > 0)
                    {
                        var dpe = ex.InnerExceptions[0] as Server.DataPortalException;
                        if (dpe != null)
                        {
                            HandleCreateDataPortalException(dpe, isSync, proxy);
                        }
                    }
                    throw new DataPortalException(
                              string.Format("DataPortal.Create {0}", Resources.Failed),
                              ex, null);
                }
                catch (Server.DataPortalException ex)
                {
                    HandleCreateDataPortalException(ex, isSync, proxy);
                }
                DataPortal.OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, criteria, DataPortalOperations.Create));
            }
            catch (Exception ex)
            {
                DataPortal.OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, criteria, DataPortalOperations.Create, ex));
                throw;
            }
            return(result.ReturnObject);
        }
Пример #12
0
    /// <summary>
    /// Called by <see cref="DataPortal" /> to delete a
    /// business object.
    /// </summary>
    /// <param name="objectType">Type of business object to create.</param>
    /// <param name="criteria">Criteria object describing business object.</param>
    /// <param name="context">
    /// <see cref="Server.DataPortalContext" /> object passed to the server.
    /// </param>
    /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
    public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync)
#pragma warning restore 1998
    {
      var request = GetBaseCriteriaRequest();
      request.TypeName = objectType.AssemblyQualifiedName;
      if (!(criteria is IMobileObject))
      {
        criteria = new PrimitiveCriteria(criteria);
      }
      request.CriteriaData = MobileFormatter.Serialize(criteria);
      request = ConvertRequest(request);

      var proxy = GetProxy();
      DataPortalResult result = null;
      try
      {
        var response = await proxy.DeleteAsync(request);
        response = ConvertResponse(response);
        var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
        if (response != null && response.ErrorData == null)
        {
          result = new DataPortalResult(null, null, globalContext);
        }
        else if (response != null && response.ErrorData != null)
        {
          var ex = new DataPortalException(response.ErrorData);
          result = new DataPortalResult(null, ex, globalContext);
        }
        else
        {
          throw new DataPortalException("null response", null);
        }
      }
      catch (Exception ex)
      {
        result = new DataPortalResult(null, ex, null);
      }
      if (result.Error != null)
        throw result.Error;
      return result;
    }
Пример #13
0
    /// <summary>
    /// Called by <see cref="DataPortal" /> to delete a
    /// business object.
    /// </summary>
    /// <param name="objectType">Type of business object to create.</param>
    /// <param name="criteria">Criteria object describing business object.</param>
    /// <param name="context">
    /// <see cref="Server.DataPortalContext" /> object passed to the server.
    /// </param>
    /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
    public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync)
#pragma warning restore 1998
    {
      var request = GetBaseCriteriaRequest();
      request.TypeName = objectType.AssemblyQualifiedName;
      if (!(criteria is IMobileObject))
      {
        criteria = new PrimitiveCriteria(criteria);
      }
      request.CriteriaData = MobileFormatter.Serialize(criteria);
      request = ConvertRequest(request);

      var proxy = GetProxy();
      DataPortalResult result = null;
      try
      {
        Csla.WcfPortal.WcfResponse response = null;
        if (isSync)
          response = proxy.Delete(request);
        else
        {
#if !NET40
          response = await proxy.DeleteAsync(request).ConfigureAwait(false);
#else
          var tcs = new TaskCompletionSource<WcfResponse>();
          proxy.DeleteCompleted += (o, e) =>
          {
            if (e.Error == null)
              tcs.TrySetResult(e.Result);
            else
              tcs.TrySetException(e.Error);
          };
          proxy.DeleteAsync(request);
          await tcs.Task;
          response = tcs.Task.Result;
#endif
        }
        response = ConvertResponse(response);
        var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
        if (response != null && response.ErrorData == null)
        {
          result = new DataPortalResult(null, null, globalContext);
        }
        else if (response != null && response.ErrorData != null)
        {
          var ex = new DataPortalException(response.ErrorData);
          result = new DataPortalResult(null, ex, globalContext);
        }
        else
        {
          throw new DataPortalException("null response", null);
        }
      }
      catch (Exception ex)
      {
        result = new DataPortalResult(null, ex, null);
      }
      if (result.Error != null)
        throw result.Error;
      return result;
    }
Пример #14
0
    /// <summary>
    /// Called by <see cref="DataPortal" /> to update a
    /// business object.
    /// </summary>
    /// <param name="obj">The business object to update.</param>
    /// <param name="context">
    /// <see cref="Server.DataPortalContext" /> object passed to the server.
    /// </param>
    /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
    public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync)
#pragma warning restore 1998
    {
#if !SILVERLIGHT && !NETFX_CORE
      ChannelFactory<IWcfPortal> cf = GetChannelFactory();
      var proxy = GetProxy(cf);
      WcfResponse response = null;
      #if NET40
      try
      {
        var request = new UpdateRequest(obj, context);
        if (isSync)
        {
          response = proxy.Update(request);
        }
        else
        {
          var worker = new Csla.Threading.BackgroundWorker();
          var tcs = new TaskCompletionSource<WcfResponse>();
          worker.RunWorkerCompleted += (o, e) =>
            {
              tcs.SetResult((WcfResponse)e.Result);
            };
          worker.DoWork += (o, e) =>
            {
              e.Result = proxy.Update(request);
            };
          worker.RunWorkerAsync();
          response = await tcs.Task;
        }
        if (cf != null)
          cf.Close();
        object result = response.Result;
        if (result is Exception)
          throw (Exception)result;
        return (DataPortalResult)result;
      }
      catch
      {
        cf.Abort();
        throw;
      }
#else
      try
      {
        var request = new UpdateRequest(obj, context);
        if (isSync)
          response = proxy.Update(request);
        else
          response = await proxy.UpdateAsync(request);
        if (cf != null)
          cf.Close();
      }
      catch
      {
        cf.Abort();
        throw;
      }
      object result = response.Result;
      if (result is Exception)
        throw (Exception)result;
      return (DataPortalResult)result;
#endif
#else
      var request = GetBaseUpdateCriteriaRequest();
      request.ObjectData = MobileFormatter.Serialize(obj);
      request = ConvertRequest(request);

      var proxy = GetProxy();
      DataPortalResult result = null;
#if !NETFX_CORE
      var tcs = new TaskCompletionSource<DataPortalResult>();
      proxy.UpdateCompleted += (s, e) => 
        {
          try
          {
            Csla.WcfPortal.WcfResponse response = null;
            if (e.Error == null)
              response = ConvertResponse(e.Result);
            ContextDictionary globalContext = null;
            if (response != null)
              globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
            if (e.Error == null && response != null && response.ErrorData == null)
            {
              var newobj = MobileFormatter.Deserialize(response.ObjectData);
              result = new DataPortalResult(newobj, null, globalContext);
            }
            else if (response != null && response.ErrorData != null)
            {
              var ex = new DataPortalException(response.ErrorData);
              result = new DataPortalResult(null, ex, globalContext);
            }
            else
            {
              result = new DataPortalResult(null, e.Error, globalContext);
            }
          }
          catch (Exception ex)
          {
            result = new DataPortalResult(null, ex, null);
          }
          finally
          {
            tcs.SetResult(result);
          }
        };
      proxy.UpdateAsync(request);
      var finalresult = await tcs.Task;
      if (finalresult.Error != null)
        throw finalresult.Error;
      return finalresult;
#else
      try
      {
        var response = await proxy.UpdateAsync(request);
        response = ConvertResponse(response);
        if (response == null)
          throw new DataPortalException("null response", null);
        var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
        if (response.ErrorData == null)
        {
          var newobj = MobileFormatter.Deserialize(response.ObjectData);
          result = new DataPortalResult(newobj, null, globalContext);
        }
        else
        {
          var ex = new DataPortalException(response.ErrorData);
          result = new DataPortalResult(null, ex, globalContext);
        }
      }
      catch (Exception ex)
      {
        result = new DataPortalResult(null, ex, null);
      }
      if (result.Error != null)
        throw result.Error;
      return result;
#endif
#endif
    }
Пример #15
0
 /// <summary>
 /// Update a business object.
 /// </summary>
 /// <param name="objectData">Business object to update.</param>
 /// <param name="contextData">
 /// Server.DataPortalContext object passed to the server.
 /// </param>
 public async Task<byte[]> Update(byte[] objectData, byte[] contextData)
 {
   DataPortalResult result;
   try
   {
     var obj = Csla.Serialization.Mobile.MobileFormatter.Deserialize(objectData);
     var context = (DataPortalContext)Csla.Serialization.Mobile.MobileFormatter.Deserialize(contextData);
     var portal = new Csla.Server.DataPortal();
     result = await portal.Update(obj, context, false);
   }
   catch (Exception ex)
   {
     result = new DataPortalResult(null, ex, null);
   }
   var response = GetDataPortalResult(result);
   var resultData = Csla.Serialization.Mobile.MobileFormatter.Serialize(response);
   return resultData;
 }
Пример #16
0
        internal async Task <T> DoUpdateAsync(T obj, bool isSync)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            Type objectType = obj.GetType();

            try
            {
                DataPortalClient.IDataPortalProxy proxy = null;
                var factoryInfo = Csla.Server.ObjectFactoryAttribute.GetObjectFactoryAttribute(objectType);
                if (factoryInfo != null)
                {
                    Csla.Server.DataPortalMethodInfo method = null;
                    var factoryLoader = ApplicationContext.CurrentServiceProvider.GetService(typeof(Server.IObjectFactoryLoader)) as Server.IObjectFactoryLoader;
                    var factoryType   = factoryLoader?.GetFactoryType(factoryInfo.FactoryTypeName);

                    if (obj is Core.ICommandObject)
                    {
                        if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.EditObject, obj))
                        {
                            throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                    "execute",
                                                                                    objectType.Name));
                        }
                        if (factoryType != null)
                        {
                            method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.ExecuteMethodName, new object[] { obj });
                        }
                    }
                    else
                    {
                        if (obj is Core.BusinessBase bbase)
                        {
                            if (bbase.IsDeleted)
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.DeleteObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "delete",
                                                                                            objectType.Name));
                                }
                                if (factoryType != null)
                                {
                                    method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.DeleteMethodName,
                                                                                        new object[] { obj });
                                }
                            }
                            // must check the same authorization rules as for DataPortal_XYZ methods
                            else if (bbase.IsNew)
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.CreateObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "create",
                                                                                            objectType.Name));
                                }
                                if (factoryType != null)
                                {
                                    method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.UpdateMethodName,
                                                                                        new object[] { obj });
                                }
                            }
                            else
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.EditObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "save",
                                                                                            objectType.Name));
                                }
                                if (factoryType != null)
                                {
                                    method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.UpdateMethodName,
                                                                                        new object[] { obj });
                                }
                            }
                        }
                        else
                        {
                            if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.EditObject, obj))
                            {
                                throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                        "save",
                                                                                        objectType.Name));
                            }

                            if (factoryType != null)
                            {
                                method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.UpdateMethodName,
                                                                                    new object[] { obj });
                            }
                        }
                    }
                    if (method == null)
                    {
                        method = new Csla.Server.DataPortalMethodInfo();
                    }
                    proxy = GetDataPortalProxy(method.RunLocal);
                }
                else
                {
                    Reflection.ServiceProviderMethodInfo method;
                    var criteria = Server.DataPortal.GetCriteriaArray(Server.EmptyCriteria.Instance);
                    if (obj is Core.ICommandObject)
                    {
                        if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.EditObject, obj))
                        {
                            throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                    "execute",
                                                                                    objectType.Name));
                        }
                        method = ServiceProviderMethodCaller.FindDataPortalMethod <ExecuteAttribute>(objectType, criteria, false);
                    }
                    else
                    {
                        if (obj is Core.BusinessBase bbase)
                        {
                            if (bbase.IsDeleted)
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.DeleteObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "delete",
                                                                                            objectType.Name));
                                }
                                method = ServiceProviderMethodCaller.FindDataPortalMethod <DeleteSelfAttribute>(objectType, criteria, false);
                            }
                            else if (bbase.IsNew)
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.CreateObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "create",
                                                                                            objectType.Name));
                                }
                                method = ServiceProviderMethodCaller.FindDataPortalMethod <InsertAttribute>(objectType, criteria, false);
                            }
                            else
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(ApplicationContext, Rules.AuthorizationActions.EditObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "save",
                                                                                            objectType.Name));
                                }
                                method = ServiceProviderMethodCaller.FindDataPortalMethod <UpdateAttribute>(objectType, criteria, false);
                            }
                        }
                        else
                        {
                            method = ServiceProviderMethodCaller.FindDataPortalMethod <UpdateAttribute>(objectType, criteria, false);
                        }
                    }
                    proxy = GetDataPortalProxy(method);
                }

                dpContext =
                    new Server.DataPortalContext(ApplicationContext, GetPrincipal(), proxy.IsServerRemote);

                try
                {
                    if (!proxy.IsServerRemote && ApplicationContext.AutoCloneOnUpdate)
                    {
                        // when using local data portal, automatically
                        // clone original object before saving
                        if (obj is ICloneable cloneable)
                        {
                            obj = (T)cloneable.Clone();
                        }
                    }
                    result = await proxy.Update(obj, dpContext, isSync);
                }
                catch (AggregateException ex)
                {
                    if (ex.InnerExceptions.Count > 0)
                    {
                        if (ex.InnerExceptions[0] is Server.DataPortalException dpe)
                        {
                            HandleUpdateDataPortalException(dpe, isSync, proxy);
                        }
                    }
                    throw new DataPortalException(
                              string.Format("DataPortal.Update {0}", Resources.Failed),
                              ex, null);
                }
                catch (Server.DataPortalException ex)
                {
                    HandleUpdateDataPortalException(ex, isSync, proxy);
                }
            }
            catch
            {
                throw;
            }
            return((T)result.ReturnObject);
        }
Пример #17
0
    /// <summary>
    /// Called by <see cref="DataPortal" /> to update a
    /// business object.
    /// </summary>
    /// <param name="obj">The business object to update.</param>
    /// <param name="context">
    /// <see cref="Server.DataPortalContext" /> object passed to the server.
    /// </param>
    /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
    public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync)
#pragma warning restore 1998
    {
      var request = GetBaseUpdateCriteriaRequest();
      request.ObjectData = MobileFormatter.Serialize(obj);
      request = ConvertRequest(request);

      var proxy = GetProxy();
      DataPortalResult result = null;
      try
      {
        var response = await proxy.UpdateAsync(request);
        response = ConvertResponse(response);
        var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
        if (response != null && response.ErrorData == null)
        {
          var newobj = MobileFormatter.Deserialize(response.ObjectData);
          result = new DataPortalResult(newobj, null, globalContext);
        }
        else if (response != null && response.ErrorData != null)
        {
          var ex = new DataPortalException(response.ErrorData);
          result = new DataPortalResult(null, ex, globalContext);
        }
        else
        {
          throw new DataPortalException("null response", null);
        }
      }
      catch (Exception ex)
      {
        result = new DataPortalResult(null, ex, null);
      }
      if (result.Error != null)
        throw result.Error;
      return result;
    }
Пример #18
0
        internal static object Fetch(Type objectType, object criteria)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            try
            {
                OnDataPortalInitInvoke(null);

                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.GetObject, objectType))
                {
                    throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                              "get",
                                                                              objectType.Name));
                }

                var method = Server.DataPortalMethodCache.GetFetchMethod(objectType, criteria);

                DataPortalClient.IDataPortalProxy proxy;
                proxy = GetDataPortalProxy(objectType, method.RunLocal);

                dpContext =
                    new Server.DataPortalContext(GetPrincipal(),
                                                 proxy.IsServerRemote);

                OnDataPortalInvoke(new DataPortalEventArgs(dpContext, objectType, DataPortalOperations.Fetch));

                try
                {
                    result = proxy.Fetch(objectType, criteria, dpContext);
                }
                catch (Server.DataPortalException ex)
                {
                    result = ex.Result;
                    if (proxy.IsServerRemote)
                    {
                        ApplicationContext.ContextManager.SetGlobalContext(result.GlobalContext);
                    }
                    string innerMessage = string.Empty;
                    if (ex.InnerException is Csla.Reflection.CallMethodException)
                    {
                        if (ex.InnerException.InnerException != null)
                        {
                            innerMessage = ex.InnerException.InnerException.Message;
                        }
                    }
                    else
                    {
                        innerMessage = ex.InnerException.Message;
                    }
                    throw new DataPortalException(
                              String.Format("DataPortal.Fetch {0} ({1})", Resources.Failed, innerMessage),
                              ex.InnerException, result.ReturnObject);
                }

                if (proxy.IsServerRemote)
                {
                    ApplicationContext.ContextManager.SetGlobalContext(result.GlobalContext);
                }

                OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, DataPortalOperations.Fetch));
            }
            catch (Exception ex)
            {
                OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, DataPortalOperations.Fetch, ex));
                throw;
            }
            return(result.ReturnObject);
        }
Пример #19
0
        internal async Task <T> DoUpdateAsync(T obj, bool isSync)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            DataPortalOperations     operation = DataPortalOperations.Update;
            Type objectType = obj.GetType();

            try
            {
                DataPortal.OnDataPortalInitInvoke(null);
                Csla.Server.DataPortalMethodInfo method = null;
                var factoryInfo = Csla.Server.ObjectFactoryAttribute.GetObjectFactoryAttribute(objectType);
                if (factoryInfo != null)
                {
                    var factoryType = Csla.Server.FactoryDataPortal.FactoryLoader.GetFactoryType(factoryInfo.FactoryTypeName);

                    if (obj is Core.ICommandObject)
                    {
                        if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                        {
                            throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                    "execute",
                                                                                    objectType.Name));
                        }
                        if (factoryType != null)
                        {
                            method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.ExecuteMethodName, new object[] { obj });
                        }
                    }
                    else
                    {
                        var bbase = obj as Core.BusinessBase;
                        if (bbase != null)
                        {
                            if (bbase.IsDeleted)
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.DeleteObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "delete",
                                                                                            objectType.Name));
                                }
                                if (factoryType != null)
                                {
                                    method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.DeleteMethodName,
                                                                                        new object[] { obj });
                                }
                            }
                            // must check the same authorization rules as for DataPortal_XYZ methods
                            else if (bbase.IsNew)
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.CreateObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "create",
                                                                                            objectType.Name));
                                }
                                if (factoryType != null)
                                {
                                    method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.UpdateMethodName,
                                                                                        new object[] { obj });
                                }
                            }
                            else
                            {
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "save",
                                                                                            objectType.Name));
                                }
                                if (factoryType != null)
                                {
                                    method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.UpdateMethodName,
                                                                                        new object[] { obj });
                                }
                            }
                        }
                        else
                        {
                            if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                            {
                                throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                        "save",
                                                                                        objectType.Name));
                            }

                            if (factoryType != null)
                            {
                                method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.UpdateMethodName,
                                                                                    new object[] { obj });
                            }
                        }
                    }
                    if (method == null)
                    {
                        method = new Csla.Server.DataPortalMethodInfo();
                    }
                }
                else
                {
                    string methodName;
                    if (obj is Core.ICommandObject)
                    {
                        methodName = "DataPortal_Execute";
                        operation  = DataPortalOperations.Execute;
                        if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                        {
                            throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                    "execute",
                                                                                    objectType.Name));
                        }
                    }
                    else
                    {
                        var bbase = obj as Core.BusinessBase;
                        if (bbase != null)
                        {
                            if (bbase.IsDeleted)
                            {
                                methodName = "DataPortal_DeleteSelf";
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.DeleteObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "delete",
                                                                                            objectType.Name));
                                }
                            }
                            else
                            if (bbase.IsNew)
                            {
                                methodName = "DataPortal_Insert";
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.CreateObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "create",
                                                                                            objectType.Name));
                                }
                            }
                            else
                            {
                                methodName = "DataPortal_Update";
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                                {
                                    throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                            "save",
                                                                                            objectType.Name));
                                }
                            }
                        }
                        else
                        {
                            methodName = "DataPortal_Update";
                            if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                            {
                                throw new Csla.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                        "save",
                                                                                        objectType.Name));
                            }
                        }
                    }
                    method = Server.DataPortalMethodCache.GetMethodInfo(obj.GetType(), methodName);
                }

                DataPortalClient.IDataPortalProxy proxy;
                proxy = GetDataPortalProxy(objectType, method.RunLocal);

                dpContext =
                    new Server.DataPortalContext(GetPrincipal(), proxy.IsServerRemote);

                DataPortal.OnDataPortalInvoke(new DataPortalEventArgs(dpContext, objectType, obj, operation));

                try
                {
                    if (!proxy.IsServerRemote && ApplicationContext.AutoCloneOnUpdate)
                    {
                        // when using local data portal, automatically
                        // clone original object before saving
                        ICloneable cloneable = obj as ICloneable;
                        if (cloneable != null)
                        {
                            obj = (T)cloneable.Clone();
                        }
                    }
                    result = await proxy.Update(obj, dpContext, isSync);
                }
                catch (AggregateException ex)
                {
                    if (ex.InnerExceptions.Count > 0)
                    {
                        var dpe = ex.InnerExceptions[0] as Server.DataPortalException;
                        if (dpe != null)
                        {
                            HandleUpdateDataPortalException(dpe, isSync, proxy);
                        }
                    }
                    throw new DataPortalException(
                              string.Format("DataPortal.Update {0}", Resources.Failed),
                              ex, null);
                }
                catch (Server.DataPortalException ex)
                {
                    HandleUpdateDataPortalException(ex, isSync, proxy);
                }

                GlobalContext = result.GlobalContext;
                if (proxy.IsServerRemote && isSync)
                {
                    ApplicationContext.ContextManager.SetGlobalContext(GlobalContext);
                }

                DataPortal.OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, obj, operation));
            }
            catch (Exception ex)
            {
                DataPortal.OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, obj, operation, ex));
                throw;
            }
            return((T)result.ReturnObject);
        }
Пример #20
0
        /// <summary>
        /// Called by the business object's Save() method to
        /// insert, update or delete an object in the database.
        /// </summary>
        /// <remarks>
        /// Note that this method returns a reference to the updated business object.
        /// If the server-side DataPortal is running remotely, this will be a new and
        /// different object from the original, and all object references MUST be updated
        /// to use this new object.
        /// </remarks>
        /// <typeparam name="T">Specific type of the business object.</typeparam>
        /// <param name="obj">A reference to the business object to be updated.</param>
        /// <returns>A reference to the updated business object.</returns>
        public static T Update <T>(T obj)
        {
            Server.DataPortalResult  result    = null;
            Server.DataPortalContext dpContext = null;
            DataPortalOperations     operation = DataPortalOperations.Update;
            Type objectType = obj.GetType();

            try
            {
                OnDataPortalInitInvoke(null);
                DataPortalMethodInfo method = null;
                var factoryInfo             = ObjectFactoryAttribute.GetObjectFactoryAttribute(objectType);
                if (factoryInfo != null)
                {
                    var factoryType = FactoryDataPortal.FactoryLoader.GetFactoryType(factoryInfo.FactoryTypeName);
                    var bbase       = obj as Core.BusinessBase;
                    if (bbase != null && bbase.IsDeleted)
                    {
                        if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.DeleteObject, obj))
                        {
                            throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                      "delete",
                                                                                      objectType.Name));
                        }
                        if (factoryType != null)
                        {
                            method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.DeleteMethodName, new object[] { obj });
                        }
                    }
                    else
                    {
                        if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                        {
                            throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                      "save",
                                                                                      objectType.Name));
                        }
                        if (factoryType != null)
                        {
                            if (obj is Core.ICommandObject)
                            {
                                method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.ExecuteMethodName, new object[] { obj });
                            }
                            else
                            {
                                method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, factoryInfo.UpdateMethodName, new object[] { obj });
                            }
                        }
                    }
                    if (method == null)
                    {
                        method = new DataPortalMethodInfo();
                    }
                }
                else
                {
                    string methodName;
                    if (obj is Core.ICommandObject)
                    {
                        methodName = "DataPortal_Execute";
                        operation  = DataPortalOperations.Execute;
                        if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                        {
                            throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                      "execute",
                                                                                      objectType.Name));
                        }
                    }
                    else
                    {
                        var bbase = obj as Core.BusinessBase;
                        if (bbase != null)
                        {
                            if (bbase.IsDeleted)
                            {
                                methodName = "DataPortal_DeleteSelf";
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.DeleteObject, obj))
                                {
                                    throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                              "delete",
                                                                                              objectType.Name));
                                }
                            }
                            else
                            if (bbase.IsNew)
                            {
                                methodName = "DataPortal_Insert";
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.CreateObject, obj))
                                {
                                    throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                              "create",
                                                                                              objectType.Name));
                                }
                            }
                            else
                            {
                                methodName = "DataPortal_Update";
                                if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                                {
                                    throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                              "save",
                                                                                              objectType.Name));
                                }
                            }
                        }
                        else
                        {
                            methodName = "DataPortal_Update";
                            if (!Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, obj))
                            {
                                throw new System.Security.SecurityException(string.Format(Resources.UserNotAuthorizedException,
                                                                                          "save",
                                                                                          objectType.Name));
                            }
                        }
                    }
                    method = Server.DataPortalMethodCache.GetMethodInfo(obj.GetType(), methodName);
                }

                DataPortalClient.IDataPortalProxy proxy;
                proxy = GetDataPortalProxy(objectType, method.RunLocal);

                dpContext =
                    new Server.DataPortalContext(GetPrincipal(), proxy.IsServerRemote);

                OnDataPortalInvoke(new DataPortalEventArgs(dpContext, objectType, operation));

                try
                {
                    if (!proxy.IsServerRemote && ApplicationContext.AutoCloneOnUpdate)
                    {
                        // when using local data portal, automatically
                        // clone original object before saving
                        ICloneable cloneable = obj as ICloneable;
                        if (cloneable != null)
                        {
                            obj = (T)cloneable.Clone();
                        }
                    }
                    result = proxy.Update(obj, dpContext);
                }
                catch (Server.DataPortalException ex)
                {
                    result = ex.Result;
                    if (proxy.IsServerRemote)
                    {
                        ApplicationContext.ContextManager.SetGlobalContext(result.GlobalContext);
                    }
                    throw new DataPortalException(
                              String.Format("DataPortal.Update {0} ({1})", Resources.Failed, ex.InnerException.InnerException),
                              ex.InnerException, result.ReturnObject);
                }

                if (proxy.IsServerRemote)
                {
                    ApplicationContext.ContextManager.SetGlobalContext(result.GlobalContext);
                }

                OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, operation));
            }
            catch (Exception ex)
            {
                OnDataPortalInvokeComplete(new DataPortalEventArgs(dpContext, objectType, operation, ex));
                throw;
            }
            return((T)result.ReturnObject);
        }
Пример #21
0
    /// <summary>
    /// Called by <see cref="DataPortal" /> to update a
    /// business object.
    /// </summary>
    /// <param name="obj">The business object to update.</param>
    /// <param name="context">
    /// <see cref="Server.DataPortalContext" /> object passed to the server.
    /// </param>
    /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
    public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync)
#pragma warning restore 1998
    {
      DataPortalResult result = null;
      try
      {
        if (isSync)
          throw new NotSupportedException("isSync == true");
        var client = GetClient();
        if (this.Timeout > 0)
          client.Timeout = TimeSpan.FromMilliseconds(this.Timeout); 
        var request = GetBaseUpdateCriteriaRequest();
        request.ObjectData = MobileFormatter.Serialize(obj);
        request = ConvertRequest(request);

        var serialized = Csla.Serialization.Mobile.MobileFormatter.Serialize(request);

        var httpRequest = new HttpRequestMessage(HttpMethod.Post, string.Format("{0}?operation=update", DataPortalUrl));
        httpRequest.Content = new ByteArrayContent(serialized);

        var httpResponse = await client.SendAsync(httpRequest);
        httpResponse.EnsureSuccessStatusCode();
        serialized = await httpResponse.Content.ReadAsByteArrayAsync();

        var response = (Csla.Server.Hosts.HttpChannel.HttpResponse)Csla.Serialization.Mobile.MobileFormatter.Deserialize(serialized);
        response = ConvertResponse(response);
        var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
        if (response != null && response.ErrorData == null)
        {
          var newobj = MobileFormatter.Deserialize(response.ObjectData);
          result = new DataPortalResult(newobj, null, globalContext);
        }
        else if (response != null && response.ErrorData != null)
        {
          var ex = new DataPortalException(response.ErrorData);
          result = new DataPortalResult(null, ex, globalContext);
        }
        else
        {
          throw new DataPortalException("null response", null);
        }
      }
      catch (Exception ex)
      {
        result = new DataPortalResult(null, ex, null);
      }
      if (result.Error != null)
        throw result.Error;
      return result;
    }
Пример #22
0
    /// <summary>
    /// Called by <see cref="DataPortal" /> to delete a
    /// business object.
    /// </summary>
    /// <param name="objectType">Type of business object to create.</param>
    /// <param name="criteria">Criteria object describing business object.</param>
    /// <param name="context">
    /// <see cref="Server.DataPortalContext" /> object passed to the server.
    /// </param>
    /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
#pragma warning disable 1998
    public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync)
#pragma warning restore 1998
    {
#if !(ANDROID || IOS) && !NETFX_CORE
      ChannelFactory<IWcfPortal> cf = GetChannelFactory();
      var proxy = GetProxy(cf);
      WcfResponse response = null;
#if NET40
      try
      {
        var request = new DeleteRequest(objectType, criteria, context);
        if (isSync)
        {
          response = proxy.Delete(request);
        }
        else
        {
          var worker = new Csla.Threading.BackgroundWorker();
          var tcs = new TaskCompletionSource<WcfResponse>();
          worker.RunWorkerCompleted += (o, e) =>
            {
              tcs.SetResult((WcfResponse)e.Result);
            };
          worker.DoWork += (o, e) =>
            {
              e.Result = proxy.Delete(request);
            };
          worker.RunWorkerAsync();
          response = await tcs.Task;
        }
        if (cf != null)
          cf.Close();
        object result = response.Result;
        if (result is Exception)
          throw (Exception)result;
        return (DataPortalResult)result;
      }
      catch
      {
        cf.Abort();
        throw;
      }
#else
      try
      {
        var request = new DeleteRequest(objectType, criteria, context);
        if (isSync)
          response = proxy.Delete(request);
        else
          response = await proxy.DeleteAsync(request);
        if (cf != null)
          cf.Close();
      }
      catch
      {
        cf.Abort();
        throw;
      }
      object result = response.Result;
      if (result is Exception)
        throw (Exception)result;
      return (DataPortalResult)result;
#endif
#else
      var request = GetBaseCriteriaRequest();
      request.TypeName = objectType.AssemblyQualifiedName;
      if (!(criteria is IMobileObject))
      {
        criteria = new PrimitiveCriteria(criteria);
      }
      request.CriteriaData = MobileFormatter.Serialize(criteria);
      request = ConvertRequest(request);

      var proxy = GetProxy();
      DataPortalResult result = null;
#if !NETFX_CORE && !(IOS || ANDROID)
      var tcs = new TaskCompletionSource<DataPortalResult>();
      proxy.DeleteCompleted += (s, e) => 
        {
          try
          {
            Csla.WcfPortal.WcfResponse response = null;
            if (e.Error == null)
              response = ConvertResponse(e.Result);
            ContextDictionary globalContext = null;
            if (response != null)
              globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
            if (e.Error == null && response != null && response.ErrorData == null)
            {
              result = new DataPortalResult(null, null, globalContext);
            }
            else if (response != null && response.ErrorData != null)
            {
              var ex = new DataPortalException(response.ErrorData);
              result = new DataPortalResult(null, ex, globalContext);
            }
            else
            {
              result = new DataPortalResult(null, e.Error, globalContext);
            }
          }
          catch (Exception ex)
          {
            result = new DataPortalResult(null, ex, null);
          }
          finally
          {
            tcs.SetResult(result);
          }
        };
      proxy.DeleteAsync(request);
      var finalresult = await tcs.Task;
      if (finalresult.Error != null)
        throw finalresult.Error;
      return finalresult;
#else
      try
      {
        var response = await proxy.DeleteAsync(request);
        response = ConvertResponse(response);
        if (response == null)
          throw new DataPortalException("null response", null);
        var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext);
        if (response.ErrorData == null)
        {
          result = new DataPortalResult(null, null, globalContext);
        }
        else
        {
          var ex = new DataPortalException(response.ErrorData);
          result = new DataPortalResult(null, ex, globalContext);
        }
      }
      catch (Exception ex)
      {
        result = new DataPortalResult(null, ex, null);
      }
      if (result.Error != null)
        throw result.Error;
      return result;
#endif
#endif
    }
Пример #23
0
 private DataPortalResult GetResult(ISerializationFormatter formatter, WcfResponse response)
 {
   response = ConvertResponse(response);
   object result = formatter.Deserialize(response.ObjectData);
   ContextDictionary globalContext = (ContextDictionary)formatter.Deserialize(response.GlobalContext);
   DataPortalResult returnValue = new DataPortalResult(result, globalContext);
   return returnValue;
 }
Пример #24
0
 private Csla.Server.Hosts.HttpChannel.HttpResponse GetDataPortalResult(DataPortalResult dataportalResult)
 {
   var result = new Csla.Server.Hosts.HttpChannel.HttpResponse();
   if (dataportalResult.Error != null)
     result.ErrorData = new HttpChannel.HttpErrorInfo(dataportalResult.Error);
   if (dataportalResult.GlobalContext != null)
     result.GlobalContext = Csla.Serialization.Mobile.MobileFormatter.Serialize(dataportalResult.GlobalContext);
   if (dataportalResult.ReturnObject != null)
     result.ObjectData = Csla.Serialization.Mobile.MobileFormatter.Serialize(dataportalResult.ReturnObject);
   return result;
 }