Example #1
0
        public virtual async Task <IServiceResponse <U> > AddAsync(U dto)
        {
            if (dto == null)
            {
                return(new ServiceResponse <U>(false, ServiceResponseMessage.Add_Null_Error <T>()));
            }

            var entity = _mapper.Map <T>(dto);

            var dataValidationResult = await ExecuteWithoutTransactionAsync <IEnumerable <IDataValidationFailure> >(async() => await _unitOfWork.Repository <T>().CanAddAsync(entity));

            if (dataValidationResult.Any())
            {
                return(new ServiceResponse <U>(false, $"Error whilst persisting {typeof(U).Name} to Database", null, dataValidationResult));
            }

            var id = await ExecuteWithTransactionAsync <int>(async() => {
                var returnValue = await _unitOfWork.Repository <T>().AddAsync(entity);
                return(returnValue);
            });

            if (id == 0)
            {
                return(new ServiceResponse <U>(false, $"Error whilst persisting {typeof(U).Name} to Database,Please contact System Administrator"));
            }

            dynamic responseDTO = GenerateResponseDTO(dto, id);

            return(new ServiceResponse <U>(true, ServiceResponseMessage.Add_Success <T>(), responseDTO));
        }
Example #2
0
        public IServiceResponseMessage List(ServiceResponseMessage<int> newRequest)
        {
            newRequest.RequestObject = 5;

            this.request = newRequest;

            return request;
        }
Example #3
0
        public ServiceResponseMessage <List <UserDTO> > GetUsersByDept(Guid deptCode)
        {
            var response = new ServiceResponseMessage <List <UserDTO> >();
            var users    = userBll.GetUsersByDeptCode(deptCode);

            response.Data = Mapper.Map <List <User>, List <UserDTO> >(users);
            return(response);
        }
Example #4
0
        public ServiceResponseMessage <List <UserDTO> > GetAllUsers()
        {
            var response = new ServiceResponseMessage <List <UserDTO> >();
            var users    = userBll.GetAllUsers();

            response.Data = Mapper.Map <List <User>, List <UserDTO> >(users);
            return(response);
        }
Example #5
0
        public virtual async Task <IServiceResponse <IEnumerable <U> > > GetAsync()
        {
            var entities = await ExecuteWithoutTransactionAsync <IEnumerable <T> >(async() => await _unitOfWork.Repository <T>().GetAsync());

            var dtos = _mapper.Map <IEnumerable <U> >(entities);

            return(new ServiceResponse <IEnumerable <U> >(true, ServiceResponseMessage.Get_Success <T>(), dtos));
        }
Example #6
0
        public virtual async Task <IServiceResponse <U> > GetByIdAsync(int id)
        {
            var entity = await ExecuteWithoutTransactionAsync <T>
                             (async() => await _unitOfWork.Repository <T>().GetByIdAsync(id, _idbHelper.GetPrimaryKeyAutoGenerated <T>()));

            var dto = _mapper.Map <U>(entity);

            return(new ServiceResponse <U>(entity != null, ServiceResponseMessage.GetById_Success <T>(), dto));
        }
Example #7
0
        public ServiceResponseMessage <List <DeptDTO> > GetAllDeparments()
        {
            var response = new ServiceResponseMessage <List <DeptDTO> >();
            var depts    = deptBll.GetAllDepts();

            response.Data = Mapper.Map <List <Dept>, List <DeptDTO> >(depts);
            Logger.Info(JsonConvert.SerializeObject(response));
            return(response);
        }
Example #8
0
        public virtual async Task <IServiceResponse <int> > DeleteAsync(int id)
        {
            var response = await ExecuteWithTransactionAsync <int>(async() => {
                var returnValue = await _unitOfWork.Repository <T>().RemoveAsync(id);

                return(returnValue);
            });

            return(new ServiceResponse <int>(response > 0, ServiceResponseMessage.Delete_Success <T>(), response));
        }
Example #9
0
        public virtual async Task <IServiceResponse <IEnumerable <U> > > GetRangeAsync(IEnumerable <int> Ids)
        {
            if (Ids == null || !Ids.Any())
            {
                return(new ServiceResponse <IEnumerable <U> >(false, ServiceResponseMessage.GetById_Success <IEnumerable <T> >()));
            }

            var response = await ExecuteWithoutTransactionAsync(async() => await _unitOfWork.Repository <T>().GetByIdRangeAsync(Ids));

            return(new ServiceResponse <IEnumerable <U> >(true, ServiceResponseMessage.Get_Success <IEnumerable <U> >(), _mapper.Map <IEnumerable <U> >(response)));
        }
Example #10
0
        /// <summary>
        /// HandleError
        /// </summary>
        /// <param name="responseStatus"></param>
        protected void HandleError(ResponseStatus responseStatus, ServiceResponseMessage responseMessage)
        {
            if (responseStatus == ResponseStatus.BusinessException)
            {
               throw new BusinessException(responseMessage.Message, responseMessage.MessageCode, responseMessage.Overridable);
            }

            else if (responseStatus == ResponseStatus.Exception)
            {
               throw new SysException(responseMessage.Message);
            }
        }
Example #11
0
        /// <summary>
        /// HandleError
        /// </summary>
        /// <param name="responseStatus"></param>
        protected void HandleError(ResponseStatus responseStatus, ServiceResponseMessage responseMessage)
        {
            if (responseStatus == ResponseStatus.BusinessException)
            {
                throw new BusinessException(responseMessage.Message, responseMessage.MessageCode, responseMessage.Overridable);
            }

            else if (responseStatus == ResponseStatus.Exception)
            {
                throw new SysException(responseMessage.Message);
            }
        }
Example #12
0
        public HttpResponseMessage Get()
        {
            var identity = this.User.Identity as ClaimsIdentity;

            if (identity == null)
            {
                return(ServiceResponseMessage.BadRequest("Could not parse identity as claims identity"));
            }

            var model = ParseClaims(identity.Claims);

            return(ServiceResponseMessage.Ok(model));
        }
Example #13
0
        public virtual async Task <IServiceResponse <int> > UpdateRangeAsync(IEnumerable <U> dtos)
        {
            if (dtos == null || !dtos.Any())
            {
                return(new ServiceResponse <int>(true, ServiceResponseMessage.UpdateRange_Success <T>(), 0));
            }

            var validDtos = dtos.Where(x => x != null);
            var entities  = _mapper.Map <IEnumerable <T> >(validDtos);

            var response = await ExecuteWithTransactionAsync <int>(async() => {
                var returnValue = await _unitOfWork.Repository <T>().UpdateRangeAsync(entities);
                return(returnValue);
            });

            return(new ServiceResponse <int>(true, ServiceResponseMessage.UpdateRange_Success <T>(), response));
        }
Example #14
0
        public ServiceResponseMessage <DeptDTO> CreateDept(DeptDTO requestDto)
        {
            var  response = new ServiceResponseMessage <DeptDTO>();
            Dept dept     = Mapper.Map <DeptDTO, Dept>(requestDto);
            bool bl       = deptBll.CreateDept(dept);

            if (bl)
            {
                response.Data = Mapper.Map <Dept, DeptDTO>(dept);
            }
            else
            {
                response.Success = false;
                response.Message = "插入数据失败";
            }
            return(response);
        }
Example #15
0
        public virtual async Task <IServiceResponse <int> > UpdateAsync(U dto)
        {
            if (dto == null)
            {
                return(new ServiceResponse <int>(false, ServiceResponseMessage.Update_Null_Error <T>()));
            }

            var entity = _mapper.Map <T>(dto);
            var dataValidationResult = await ExecuteWithoutTransactionAsync <IEnumerable <IDataValidationFailure> >(async() => await _unitOfWork.Repository <T>().CanUpdateAsync(entity));

            if (dataValidationResult.Any())
            {
                return(new ServiceResponse <int>(false, $"Error whilst persisting {typeof(U).Name} to Database", 0, dataValidationResult));
            }

            var response = await ExecuteWithTransactionAsync <int>(async() => {
                var returnValue = await _unitOfWork.Repository <T>().UpdateAsync(entity);
                return(returnValue);
            });

            return(new ServiceResponse <int>(response == 1, response == 1 ? ServiceResponseMessage.Update_Success <T>() : ServiceResponseMessage.Update_Nonexistent_Error <T>(), response == 1 ? response : (int)_idbHelper.GetKeyValue(entity, _idbHelper.GetPrimaryKeyAutoGenerated <T>())));
        }
        protected override bool HandleRosbridgeMessage(JObject rosbridgeMessage, ref JObject rosMessage, string serviceName = null)
        {
            string serviceToReceiveFrom = serviceName ?? this.ServiceName;

            ServiceResponseMessage serviceResponse = null;

            try
            {
                serviceResponse = rosbridgeMessage.ToObject <ServiceResponseMessage>();
            }
            catch (JsonSerializationException e)
            {
            }

            if (serviceResponse != null && object.Equals(serviceResponse.Service, serviceToReceiveFrom) && object.Equals(this.MessageId, serviceResponse.Id))
            {
                if (serviceResponse.Values != null)
                {
                    if (serviceResponse.Values.Type == JTokenType.Object)
                    {
                        if (serviceResponse.Values.HasValues)
                        {
                            JObject responseObject = (JObject)serviceResponse.Values;

                            rosMessage = responseObject;
                        }

                        return(true);
                    }
                    else if (serviceResponse.Values.Type == JTokenType.String)
                    {
                        throw new RosServiceException(serviceResponse.Values.ToString());
                    }
                }
            }

            return(false);
        }
Example #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new HttpResponseException(
                          new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("HttpRequestMessage is null.")
                });
            }

            var context = await request.GetSTSRequestContextAsync();

            if (!ValidateContext(context))
            {
                throw new HttpResponseException(ServiceResponseMessage.Unauthorized());
            }

            request.Properties.Add(STSConstants.STSRequestContext, context);

            return(await base.SendAsync(request, cancellationToken));
        }
Example #18
0
 public override void ResponseFunction(string m)
 {
     receive_data = ParseMessage(m);
     Handler(receive_data.values);
 }
Example #19
0
        /// <summary>
        /// POST to STS to get a Bearer Token
        /// </summary>
        /// <returns>An OAuth2 Bearer Token</returns>
        public async Task <HttpResponseMessage> Post()
        {
            try
            {
                var requestContext = this.Request.Properties[STSConstants.STSRequestContext] as ITokenServiceRequestContext;
                if (requestContext == null)
                {
                    throw new HttpResponseException(ServiceResponseMessage.BadRequest("STS Context is null"));
                }

                // Create Identity and Set Claims
                var authType = OwinStartUp.OAuthBearerOptions.AuthenticationType;
                var identity = new ClaimsIdentity(authType);

                /// LEFTOFF - make this code cleaner, create type by version (type converter). Also take authprovider,
                /// start building simple factory and inject providers
                if (requestContext.Version == 1.0)
                {
                    // push auth rules to plug ins and take a provider/default provider and pass provider in request

                    var body = requestContext.TokenRequestBody as TokenRequestV1;
                    // TODO: validate the parts
                    identity.AddClaim(new Claim(ClaimTypes.Name, body.UserName));
                    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()));
                    identity.AddClaim(new Claim(ClaimTypes.Email, body.Email));
                    identity.AddClaim(new Claim(ClaimTypes.MobilePhone, body.MobilePhone));
                    identity.AddClaim(new Claim(ClaimTypes.Authentication, "Partial"));
                }

                var properties = new AuthenticationProperties
                {
                    IsPersistent = false
                };

                var ticket = new AuthenticationTicket(identity, properties);

                var currentUtc = new SystemClock().UtcNow;
                ticket.Properties.IssuedUtc = currentUtc;

                // Set expiration
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

                // TODO: ticket needs to be signed with a certificate. Create new signing cert and use that same cert of other services.
                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(OwinStartUp.OAuthBearerOptions.AccessTokenFormat.Protect(ticket))
                });
            }
            catch (Exception ex)
            {
                // Test all of these exceptions
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(ex.Message)
                });
            }
            finally
            {
                // Log event
            }
        }
Example #20
0
        /// <summary>
        /// POST to STS to get an OAuth Token
        /// </summary>
        /// <returns>An OAuth2 Token</returns>
        public async Task <HttpResponseMessage> Post()
        {
            try
            {
                var requestContext = this.Request.Properties[STSConstants.STSRequestContext] as ITokenServiceRequestContext;
                if (requestContext == null)
                {
                    throw new HttpResponseException(ServiceResponseMessage.BadRequest("STS Context is null"));
                }

                // Create Identity and Set Claims
                var authType = OwinStartUp.OAuthBearerOptions.AuthenticationType;
                var identity = new ClaimsIdentity(authType);

                if (requestContext.Version == 1.0)
                {
                    var body = requestContext.TokenRequestBody as TokenRequestV1;
                    if (body == null)
                    {
                        return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                        {
                            Content = new StringContent("Could not parse request body")
                        });
                    }

                    //identity.AddClaim(new Claim(ClaimTypes.Name, body.UserName));
                    //identity.AddClaim(new Claim(ClaimTypes.Email, body.Email));
                    //identity.AddClaim(new Claim(ClaimTypes.MobilePhone, body.MobilePhone));
                    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()));

                    var auth = ServiceLocator.Instance.GetAuthenticationProvider(body.AuthenticationProvider);
                    if (auth == null)
                    {
                        return(ServiceResponseMessage.BadRequest("Invalid Authentication Provider passed"));
                    }

                    // Call the auth provider here
                    if (!body.AuthenticationProvider.Equals("none", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (!await auth.IsAuthenticatedAsync(body.Email, body.Password))
                        {
                            return(ServiceResponseMessage.Unauthorized());
                        }
                        else
                        {
                            identity.AddClaim(new Claim(ClaimTypes.Authentication, "Full"));
                        }
                    }
                }

                var ticket = new AuthenticationTicket(identity, new AuthenticationProperties
                {
                    IsPersistent = false
                });
                var currentUtc = new SystemClock().UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

                var token   = OwinStartUp.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
                var bytes   = Encoding.UTF8.GetBytes(token);
                var encoded = "NORD " + Convert.ToBase64String(bytes);

                return(ServiceResponseMessage.Ok(encoded));
            }
            catch (Exception ex)
            {
                // Test all of these exceptions
                return(ServiceResponseMessage.InternalServerError(ex.Message));
            }
            finally
            {
                // Log event
            }
        }
Example #21
0
        public void Connect()
        {
            if (!isConnected)
            {
                ws         = new WebSocket("ws://" + IPAddress + ":" + Port + "/");
                ws.OnOpen += (sender, e) =>
                {
                    Debug.Log("WebSocket Opened.");
                    isConnected = true;
                };

                ws.OnMessage += (sender, e) =>
                {
                    OperationMessage data = JsonUtility.FromJson <OperationMessage>(e.Data);
                    if (data.op == "publish")
                    {
                        SubscribeMessage msg = JsonUtility.FromJson <SubscribeMessage>(e.Data);
                        foreach (SubscribeManager sm in subscribeManagers)
                        {
                            if (msg.topic == sm.Topic)
                            {
                                if (!sm.IsRunning)
                                {
                                    sm.HandlerFunction(e.Data);
                                }
                            }
                        }
                    }

                    else if (data.op == "service_response")
                    {
                        ServiceResponseMessage msg = JsonUtility.FromJson <ServiceResponseMessage>(e.Data);
                        foreach (ServiceClientManager sc in serviceClientManagers)
                        {
                            if (msg.service == sc.service_name)
                            {
                                sc.ResponseFunction(e.Data);
                            }
                        }
                    }

                    else if (data.op == "call_service")
                    {
                        CallServiceMessage msg = JsonUtility.FromJson <CallServiceMessage>(e.Data);
                        foreach (var ss in serviceServerManagers)
                        {
                            if (msg.service == ss.service)
                            {
                                ss.HandlerFunction(e.Data);
                            }
                        }
                    }
                };

                ws.OnError += (sender, e) =>
                {
                    Debug.Log("WebSocket Error Message: " + e.Message);
                };

                ws.OnClose += (sender, e) =>
                {
                    Debug.Log("WebSocket Closed.");
                    isConnected = false;
                };

                if (IsConnectable())
                {
                    ws.Connect();
                }
            }
        }