Esempio n. 1
0
 /// <summary>
 /// Initialise a new instance of <see cref="Response"/> from a response.
 /// </summary>
 /// <param name="response">The response to use.</param>
 public Response(Response response)
 {
     errorMessages = response.errorMessages;
     requestIdentifier = response.requestIdentifier;
     result = response.result;
     Timestamp = response.Timestamp;
 }
        public IHttpActionResult UnSubscribe(GCMSubscriptionModel model)
        {
            var result = new ResponseResult(Constants.InvalidCommand);

            var command = model.AsUnSubscribeCommand();
            if (command.IsValid())
            {
                result = Publisher.Publish(command)
                    ? new ResponseResult<ResponseResult>(new ResponseResult())
                    : new ResponseResult(Constants.CommandPublishFailed);
            }
            return result.IsSuccess
                ? this.Accepted(result)
                : this.NotAcceptable(result);
        }
Esempio n. 3
0
        private async Task AssertInvoices(ResponseResult <string, ResultErrorCode> sendInvoicesResults)
        {
            TestFixture.AssertResponse(sendInvoicesResults);

            Thread.Sleep(2000);

            var transactionId     = sendInvoicesResults.SuccessResult;
            var transactionStatus = await NavClient.GetTransactionStatusAsync(transactionId);

            TestFixture.AssertResponse(transactionStatus);

            var invoiceStatuses = transactionStatus.SuccessResult.InvoiceStatuses;

            foreach (var status in invoiceStatuses)
            {
                var value = status.Value;
                Assert.AreEqual(value.Status, InvoiceState.Done);
            }

            var validationResults = invoiceStatuses.SelectMany(s => s.Value.ValidationResults);

            Assert.IsEmpty(validationResults);
        }
Esempio n. 4
0
        public ResponseResult UpdateProcess(ProcessEntity entity)
        {
            var result = ResponseResult.Default();

            try
            {
                var wfService     = new WorkflowService();
                var processEntity = wfService.GetProcessByVersion(entity.ProcessGUID, entity.Version);
                processEntity.ProcessName = entity.ProcessName;
                processEntity.XmlFileName = entity.XmlFileName;
                processEntity.AppType     = entity.AppType;
                processEntity.Description = entity.Description;

                wfService.UpdateProcess(processEntity);

                result = ResponseResult.Success();
            }
            catch (System.Exception ex)
            {
                result = ResponseResult.Error(string.Format("更新流程记录失败,错误:{0}", ex.Message));
            }
            return(result);
        }
Esempio n. 5
0
        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="LoginName"></param>
        /// <param name="Password"></param>
        /// <param name="IP"></param>
        /// <returns></returns>
        public string Login([FromForm] LoginFrom fromData)
        {
            var model = _BaseServer.Login(fromData);
            Func <ResponseResult> funcAction = () =>
            {
                var    responseModel = new ResponseResult();
                Result result        = new Result();
                if (model != null)
                {
                    responseModel.Token      = BaseService.Insert(model, HttpContext);
                    result.IsSuccessful      = true;
                    result.ReasonDescription = "登录成功!";
                }
                else
                {
                    result.ReasonDescription = "用户名或密码错误!";
                }
                responseModel.Content = result;
                return(responseModel);
            };

            return(ActionResponseGetString(funcAction));
        }
        public ResponseResult SearchUser(string key)
        {
            try
            {
                var list = DataService.SearchUser(key);

                var result = (from p in list
                              select new
                {
                    ID = p.UserId,
                    Login = p.Login,
                    Name = p.Name
                }).ToList();

                return(ResponseResult.GetSuccessObject(result));
                //return result;
            }
            catch (Exception ex)
            {
                CustomUtility.HandleException(ex);
                return(ResponseResult.GetErrorObject());
            }
        }
Esempio n. 7
0
        public async override Task <IResponseResult> AddAsync(UserDto model)
        {
            if (model == null)
            {
                return(ResponseResult.GetRepositoryActionResult(status: HttpStatusCode.NoContent, message: HttpStatusCode.NoContent.ToString()));
            }
            var isExist = await _unitOfWork.Repository.IsExists(q => (q.UserName == model.UserName || q.Email == model.Email || (q.PhoneNumber == model.PhoneNumber && (model.PhoneNumber != "" && model.PhoneNumber != null))) && q.IsDeleted != true);

            if (isExist)
            {
                return(ResponseResult.GetRepositoryActionResult(status: HttpStatusCode.NotAcceptable, message: HttpStatusCode.NotAcceptable.ToString()));
            }
            var data = await _unitOfWork.Repository.FindAsync(q => q != null);

            model.Id            = data == null ? 1000 : (1000 + data.Count());
            model.SecurityStamp = Guid.NewGuid().ToString();
            var user = Mapper.Map <AspNetUsers>(model);

            _unitOfWork.Repository.Add(user);
            await _unitOfWork.SaveChanges();

            return(ResponseResult.GetRepositoryActionResult(model, status: HttpStatusCode.Created, message: HttpStatusCode.Created.ToString()));
        }
Esempio n. 8
0
 private async Task<ResponseResult> upload(string file,string dst)
 {
             
     ResponseResult r=new ResponseResult();
     try
     {
         r = CHFSApi.CHFSApi.Exist(file, dst + "/");
         if (r.code != 404)
         {
             //  MessageBox.Show(file + "已存在!");
             r.code = 500;
             return r;
         }
         r = await CHFSApi.CHFSApi.Upload(file, dst);
         return r;
     }
     catch
     {
         r.code = 500;
         return r;
     }
     
 }
Esempio n. 9
0
        public ResponseResult RunProcess([FromBody] WfAppRunner runner)
        {
            var result    = ResponseResult.Default();
            var wfService = new WorkflowService();

            try
            {
                var wfResult = wfService.RunProcessApp(runner);
                if (wfResult.Status == WfExecutedStatus.Success)
                {
                    result = ResponseResult.Success(wfResult.Message);
                }
                else
                {
                    result = ResponseResult.Error(wfResult.Message);
                }
            }
            catch (System.Exception ex)
            {
                result = ResponseResult.Error(ex.Message);
            }
            return(result);
        }
Esempio n. 10
0
        public HttpResponseMessage Get(string size, string id)
        {
            using (var picturesService = new PicturesService())
            {
                FileStream fileStream = null;
                HttpResponseMessage result ;
                string rootPath = HttpContext.Current.Server.MapPath("~/data/pics");
                PicSize picSize = (PicSize)Enum.Parse(typeof(PicSize), size);
                using (picturesService.GetImageStream(rootPath, picSize,id, out fileStream))
                {
                    if (fileStream.CanRead)
                    {
                        int length = (int)fileStream.Length;
                        byte[] buffer = new byte[length];
                        fileStream.Read(buffer, 0, length);

                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        result.Content = new ByteArrayContent(buffer);
                        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                        return result;
                    }
                    else
                    {
                        var content = new ResponseResult<string>
                        {
                            Errors = new List<string>() { "Image not found" },
                            Result = null,
                            Succeed = true
                        };
                        result = new HttpResponseMessage(HttpStatusCode.NotFound);
                        result.Content = new ObjectContent<ResponseResult<string>>(content, new JsonMediaTypeFormatter());
                        return result;
                    }
                }
            }

        }
Esempio n. 11
0
        public ResponseResult CheckJobOrder(string jobno)
        {
            response = new ResponseResult();

            try
            {
                ProcParam procPara = new ProcParam(3)
                {
                    ProcedureName = "SCANNER_MAT_CHK_PACK.CHK_JOB_ORDER"
                };

                procPara.AddParamReturn(0, "ReturnValue", OracleDbType.Varchar2, 30);
                procPara.AddParamInput(1, "strJOB_NO", jobno);
                procPara.AddParamOutput(2, "RESULTMSG", OracleDbType.Varchar2, 255);

                GlobalDB.Instance.DataAc.ExecuteNonQuery(procPara);

                if (GlobalDB.Instance.DataAc.LastException != null)
                {
                    throw GlobalDB.Instance.DataAc.LastException;
                }

                var returnValue = (OracleString)procPara.ReturnValue(0);
                var resultMsg   = (OracleString)procPara.ReturnValue(2);

                response.Message = resultMsg.ToString();
                response.Data    = returnValue.ToString();
            }
            catch (Exception ex)
            {
                response.Status  = false;
                response.Message = ex.Message;
                response.Data    = string.Empty;
            }

            return(response);
        }
Esempio n. 12
0
        private async Task <ResponseResult <T> > GettingStandardResponse <T>(HttpResponseMessage response)
        {
            var res = new ResponseResult <T>();

            if (response.IsSuccessStatusCode)
            {
                res.StatusCode = 200;
                res.Status     = "Success";
                res.Message    = "Call success";
                var settings = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };
                var responseContent = await response.Content.ReadAsStringAsync();

                res.Data = JsonConvert.DeserializeObject <T>(responseContent, settings);
            }
            else if (response.StatusCode >= System.Net.HttpStatusCode.BadRequest && response.StatusCode < System.Net.HttpStatusCode.InternalServerError)
            {
                res.StatusCode = 400;
                res.Status     = "BadRequest";
                res.Data       = default(T);
                var badResponseContent = await response.Content.ReadAsStringAsync();

                res.Message = JsonConvert.DeserializeObject <BadRequestResponseResult>(badResponseContent).Message;
            }
            else if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError)
            {
                res.StatusCode = 500;
                res.Status     = "InternalServerError";
                res.Data       = default(T);
                //res.Message = response.ReasonPhrase;
                res.Message = await response.Content.ReadAsStringAsync();
            }
            return(res);
        }
Esempio n. 13
0
        public ResponseResult TaskBind(string taskName, string routeName, string loginName, string shipName)
        {
            var         result      = ResponseResult.Default();
            TaskService taskService = new TaskService();

            try
            {
                if (string.IsNullOrEmpty(routeName))
                {
                    return(ResponseResult.Error("路径不能为空"));
                }
                if (string.IsNullOrEmpty(taskName))
                {
                    return(ResponseResult.Error("任务名称不能为空"));
                }
                if (string.IsNullOrEmpty(loginName))
                {
                    return(ResponseResult.Error("登录名称不能为空"));
                }
                if (string.IsNullOrEmpty(shipName))
                {
                }
                if (taskService.RouteChange(taskName, routeName, loginName, shipName))
                {
                    return(ResponseResult.Success("绑定成功"));
                }
                else
                {
                    return(ResponseResult.Error("绑定失败"));
                }
            }
            catch (System.Exception ex)
            {
                result = ResponseResult.Error(ex.Message);
            }
            return(result);
        }
Esempio n. 14
0
        public ResponseResult SaveRole(Roles r)
        {
            String msg = " ";

            try
            {
                var roleId = DataService.SaveRole(r, DateTime.UtcNow, SessionManager.CurrentUser.UserId);
                if (r.Id > 0)
                {
                    msg = "Role Updated Successfully";
                }
                if (r.Id == 0)
                {
                    msg = "Role added Successfully";
                }

                return(ResponseResult.GetSuccessObject(new
                {
                    RoleId = roleId
                }, msg));

                //return (new
                //{
                //    data = new
                //    {
                //        RoleId = roleId
                //    },
                //    success = true,
                //    error = msg
                //});
            }
            catch (Exception ex)
            {
                CustomUtility.HandleException(ex);
                return(ResponseResult.GetErrorObject());
            }
        }
Esempio n. 15
0
        public async Task <ServiceResponse <ProductDto_ToReturn> > NewProduct(ProductDto_ToCreate newProduct)
        {
            string errorMessage = "";

            if (newProduct.Price == 0)
            {
                errorMessage += "Please enter price field";
                return(ResponseResult.Failure <ProductDto_ToReturn>(errorMessage));
            }
            if (newProduct.ProductGroupId == 0)
            {
                errorMessage += "Please enter product group id field";
                return(ResponseResult.Failure <ProductDto_ToReturn>(errorMessage));
            }

            var checkProduct = await _dbContext.Products.FirstOrDefaultAsync(x => x.Name == newProduct.Name);

            if (checkProduct == null)
            {
                var product = new mProduct
                {
                    Name           = newProduct.Name,
                    Price          = newProduct.Price,
                    CreatedDate    = Now(),
                    IsActive       = true,
                    ProductGroupId = newProduct.ProductGroupId,
                };
                _dbContext.Products.Add(product);
                await _dbContext.SaveChangesAsync();

                return(ResponseResult.Success(_mapper.Map <ProductDto_ToReturn>(product)));
            }
            else
            {
                return(ResponseResult.Failure <ProductDto_ToReturn>("There is already a product group with the same name."));
            }
        }
Esempio n. 16
0
        public ResponseResult MakeABooking(int id, [FromBody] int NumberOfRooms)
        {
            ResponseResult responseResult = new ResponseResult();
            Status         statusObject   = new Status();

            responseResult.StatusObject = statusObject;
            try
            {
                int          loop;
                HotelBooking obj = new HotelBooking();
                for (loop = 0; loop < DataValues.Count; loop++)
                {
                    if (DataValues[loop].Id == id)
                    {
                        DataValues[loop].NumberOfAvailableRooms = DataValues[loop].NumberOfAvailableRooms - NumberOfRooms;
                        break;
                    }
                }
                if (loop == DataValues.Count)
                {
                    throw new Exception("Hotel not Found");
                }
                responseResult.StatusObject.actionStatus    = "Success";
                responseResult.StatusObject.Code            = 200;
                responseResult.StatusObject.responseMessage = "Booking Made Successfully";
                responseResult.hotelObject = DataValues[loop];
                return(responseResult);
            }
            catch (Exception e)
            {
                responseResult.StatusObject.actionStatus    = "Failure";
                responseResult.StatusObject.Code            = 404;
                responseResult.StatusObject.responseMessage = "Booking Failed as Hotel not Found";
                responseResult.hotelObject = null;
                return(responseResult);
            }
        }
Esempio n. 17
0
        public ActionResult Index([FromForm] LoginRequest login)
        {
            if (_session.GetString("name") != null && !Request.IsAjaxRequest())
            {
                return(GoToDefualt());
            }
            ResponseResult responseResult = new ResponseResult(true, null);

            if (login.name == null || login.password == null)
            {
                responseResult = new ResponseResult(false, "用户名和密码不能为空");
                return(Json(responseResult));
            }
            AccountDto userDto = AccountBusiness.GetAccountByName(login.name);

            if (userDto == null)
            {
                responseResult = new ResponseResult(false, "用户名不正确");
                return(Json(responseResult));
            }
            string saltPassword = LoginHelper.GetSaltPassword(login.password, userDto.Salt);

            if (userDto.Name != login.name || userDto.Password != saltPassword)
            {
                responseResult = new ResponseResult(false, "密码不正确");
                return(Json(responseResult));
            }

            LoginHelper.Login(new LoginModel {
                name     = login.name,
                password = login.password,
                rolename = userDto.RoleId.ToString()
            }, _session);

            responseResult = new ResponseResult(true, "/App/Index");
            return(Json(responseResult));
        }
Esempio n. 18
0
        public async Task <IActionResult> Post(ArticleDto articleDto)
        {
            bool isNew = articleDto.Id <= 0 ? true : false;


            if (articleDto.State == ArticleState.Published && !articleDto.PublishTime.HasValue)
            {
                articleDto.PublishTime = DateTime.Now;
            }
            var id = await _articleService.AddOrUpdateArticle(articleDto);

            Task.Run(

                async() => {
                var article     = await _articleService.GetArticle(id);
                var indexConfig = new LuceneIndexable <ArticleDto, int>(
                    article,
                    article.Id,
                    new LuceneIndexBehavior <ArticleDto>()
                    .Include(new Expression <Func <ArticleDto, object> >[] { a => a.Id, a => a.CreateDate, a => a.CreateDate, a => a.LastModifyDate, a => a.Summary, a => a.Title, a => a.ArticleContentHtml })
                    .ForMember(a => a.ArticleContentHtml, html => html == null ? null : html.NoHTML(), a => true)
                    .ForMember(a => a.Id, null, id => true)
                    );
                if (isNew)
                {
                    _searchEngine.LuceneIndexer.Add(indexConfig);
                }
                else
                {
                    _searchEngine.LuceneIndexer.Update(indexConfig);
                }
            }
                );
            var result = new ResponseResult <int>(id);

            return(Ok(result));
        }
Esempio n. 19
0
        public async Task <ServiceResponse <ProductDTO> > Add(ProductAddDTO addProduct)
        {
            // User must be presented to perform this method
            if (String.IsNullOrEmpty(GetUserId()))
            {
                throw new UnauthorizedAccessException("User must be presented to perform this method");
            }

            var productGroup = await _dbContext.ProductGroup.FindAsync(addProduct.GroupId);

            if (productGroup is null)
            {
                throw new InvalidOperationException("Product Group is not Exist");
            }

            // Add Products
            Product product = _mapper.Map <Product>(addProduct);

            product.Group           = productGroup;
            product.CreatedByUserId = Guid.Parse(GetUserId());
            product.CreatedDate     = Now();
            product.Status          = true;

            await _dbContext.Product.AddAsync(product);

            await _dbContext.SaveChangesAsync();

            // Mapping
            var dto = _mapper.Map <ProductDTO>(product);

            // Add User Detail
            dto.CreatedByUserID   = Guid.Parse(GetUserId());
            dto.CreatedByUserName = GetUsername();

            // Return result
            return(ResponseResult.Success <ProductDTO>(dto));
        }
Esempio n. 20
0
        public JsonResult PublishedForFarmerbyTime(int pageIndex, int pageSize, int type, string orderfield)
        {
            using (ResponseResult <List <PublishedModel> > result = new ResponseResult <List <PublishedModel> >())
            {
                pageIndex = pageIndex == 0 ? 1 : pageIndex;
                long TotalNums = 0;

                if (type != 0)
                {
                    if (_commonRepository.CheckTypeid <T_SYS_DICTIONARY>(s => s.Code == type && s.ParentCode == 100200))
                    {
                        //获取发布列表
                        List <PublishedModel> list = repository.GetRequirementListByTime(type, orderfield, pageIndex, pageSize, out TotalNums);
                        if (list != null)
                        {
                            result.Entity = list;
                        }
                        result.IsSuccess = true;
                    }
                    else
                    {
                        result.IsSuccess = false;
                        result.Message   = String.Format("{0} - " + ResponeString.ParmetersInvalidMessage, type.ToString());
                    }
                }
                else
                {
                    result.IsSuccess = false;
                    result.Message   = ResponeString.AddressError;
                }

                result.TotalNums = TotalNums;
                result.PageIndex = pageIndex;
                result.PageSize  = pageSize;
                return(Json(result));
            }
        }
Esempio n. 21
0
    /// <summary>
    /// post a status with location info
    /// </summary>
    /// <param name="txt">content of the status, less than 140 characters.</param>
    /// <param name="lat">latitude from -90.0 to 90.0 default is 0.0</param>
    /// <param name="log">longitude from -180.0 to 180.0, default is 0.0 </param>
    /// <returns>void</returns>
    public void Share(string txt, float lat, float log)
    {
        Task task;
        List <HttpParameter> config = new List <HttpParameter> ()
        {
            new HttpParameter("oauth_consumer_key", appKey),
            new HttpParameter("oauth_version", "2.a"),
            new HttpParameter("format", "json"),
            new HttpParameter("content", txt),
            new HttpParameter("clientip", "127.0.0.1"),
            new HttpParameter("longitude", lat),
            new HttpParameter("latitude", log)
        };

//		Debug.Log("access_token=" + accessToken);
//		Debug.Log("Shareopenid=" + openID);
        task.commandType   = T_ADD;
        task.requestMethod = RequestMethod.Post;
        task.parameters    = config;
        //check if accesstoken expired
        if (!oauth.VerifierAccessToken())
        {
            ResponseResult result = new ResponseResult();
            result.platformType = PlatformType.PLATFORM_TENCENTWEIBO;
            result.returnType   = ReturnType.RETURNTYPE_OAUTH_FAILED;
            result.commandType  = task.commandType;
            result.description  = "invalid accessToken";
            lock (resultList) {
                resultList.Add(result);
            }
        }
        else
        {
            Debug.Log("oauth.AccessToken----" + oauth.AccessToken);
            SendCommand(task);
        }
    }
Esempio n. 22
0
        public ResponseResult SavePermission(PermissionsWithRoleID p)
        {
            String msg = " ";

            try
            {
                var permId = DataService.SavePermission(p, DateTime.UtcNow, SessionManager.CurrentUser.UserId);
                if (p.Id > 0)
                {
                    msg = "Permission Updated Successfully";
                }
                if (p.Id == 0)
                {
                    msg = "Permission Added Successfully";
                }

                return(ResponseResult.GetSuccessObject(new
                {
                    PermssionId = permId
                }, msg));

                //return (new
                //{
                //    data = new
                //    {
                //        PermssionId = permId
                //    },
                //    success = true,
                //    error = msg
                //});
            }
            catch (Exception ex)
            {
                CustomUtility.HandleException(ex);
                return(ResponseResult.GetErrorObject());
            }
        }
Esempio n. 23
0
        /// <summary>
        /// 初始化时生成下拉框
        /// </summary>
        /// <param name="inparams"></param>
        /// <returns></returns>
        public ResponseResult getAllCmbOnLoad(Dictionary <string, string> inparams)
        {
            ResponseResult Result = null;
            string         sysflag;

            if (!inparams.Keys.Contains("sysflag") || !inparams.Keys.Contains("sysuid"))
            {
                Result = new ResponseResult(ResState.ParamsImperfect, "缺少参数", null);
                return(Result);
            }
            try
            {
                if (inparams["sysflag"] == "")
                {
                    Result = new ResponseResult(ResState.ParamsImperfect, "系统标识错误", null);
                    return(Result);
                }

                sysflag = inparams["sysflag"];

                //调用方法取得下拉框数据表格
                DataTable[] dtArr = GetAllCmb(sysflag);
                int         Total = dtArr.Length;
                ResList     res   = new ResList();
                res.page         = 0;
                res.size         = 0;
                res.total        = Total;
                res.records      = dtArr;
                res.isallresults = 0;
                Result           = new ResponseResult(ResState.Success, "", res);
            }
            catch (Exception ex)
            {
                Result = new ResponseResult(ResState.OperationFailed, ex.Message, "");
            }
            return(Result);
        }
Esempio n. 24
0
        public JsonResult UpdateRole([FromForm]  WXQ.InOutPutEntites.Input.SystemManage.Role.UpdateRoleInput model)
        {
            ResponseResult result = new ResponseResult();

            UpdateRoleInputModelValidation validator = new UpdateRoleInputModelValidation();
            ValidationResult vr = validator.Validate(model);

            if (!vr.IsValid)
            {
                result.Code   = ResponseResultMessageDefine.ParaError;
                result.Errors = vr.Errors.Select(e => e.ErrorMessage).ToList();
            }
            else
            {
                int userId = WebApi.Common.HelpOp.UserOp.GetUserId(this.User);
                WXQ.BusinessCore.systemmanage.RoleOp op = new WXQ.BusinessCore.systemmanage.RoleOp(userId);

                WXQ.Enties.Role r = new WXQ.Enties.Role
                {
                    RoleId      = model.RoleId,
                    AddDateTime = DateTime.Now,
                    AddUser     = userId.ToString(),
                    Description = model.Description,
                    RoleName    = model.RoleName
                };

                bool rv = op.UpdateRole(r);

                if (!rv)
                {
                    result.Code = ResponseResultMessageDefine.OpLost;
                    result.Errors.Add(ResponseResultMessageDefine.OpLostMessage);
                }
            }

            return(Json(result));
        }
Esempio n. 25
0
        public ActionResult LogIn(long phone, string password)
        {
            try
            {
                UserLogInRequestVM userLogInRequestVMObj = new UserLogInRequestVM()
                {
                    Phone    = phone,
                    Password = password
                };

                object         res               = _apiRequestObj.HttpPostRequest(userLogInRequestVMObj, "api/Security/UserLogin");
                string         response          = res.ToString();
                ResponseResult responseResultObj = JsonConvert.DeserializeObject <ResponseResult>(response);

                if (responseResultObj.MessageCode == "Y")
                {
                    UserLogInInfoVM userInfo = JsonConvert.DeserializeObject <UserLogInInfoVM>(responseResultObj.Content.ToString());
                    //SessionInitialize(userInfo);
                    SessionInitialize(userInfo);
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    TempData["msgAlert"]        = "NotAuthorized";
                    TempData["msgAlertDetails"] = responseResultObj.SystemMessage.ToString();
                    //Session["LogInUserInfo"] = null;
                    return(RedirectToAction("LogIn"));
                }
            }
            catch (Exception ex)
            {
                TempData["msgAlert"]        = "N";
                TempData["systemErrorMsg"]  = ex.Message;
                TempData["msgAlertDetails"] = "Sorry, something wrong. Please wait and try after a few minutes.";
                return(RedirectToAction("LogIn"));
            }
        }
Esempio n. 26
0
        public ResponseResult Run()
        {
            var runner = _appRunner;

            var result = ResponseResult.Default();

            try
            {
                string           amount    = string.Empty;
                IWorkflowService wfService = new WorkflowService();
                //var wfResult = wfService.CreateRunner(runner)

                //            .Run();
                var wfResult = wfService.CreateRunner(runner.UserID, runner.UserName)
                               .UseApp(runner.AppInstanceID, runner.AppName, runner.AppInstanceCode)
                               .UseProcess(runner.ProcessGUID, runner.Version)
                               //.NextStep(runner.NextActivityPerformers)
                               //.NextStepInt(NextPerformerIntTypeEnum.Single)
                               .IfCondition(runner.Conditions)
                               .Subscribe(EventFireTypeEnum.OnActivityExecuting, (delegateContext, delegateService) => {
                    if (delegateContext.ActivityCode == "Task1")
                    {
                        delegateService.SaveVariable(ProcessVariableTypeEnum.Process, "name", "book-task1");
                        delegateService.SaveVariable(ProcessVariableTypeEnum.Process, "amount", "50");
                    }
                    return(true);
                })
                               .Run();

                result = ResponseResult.Success(wfResult.Message);
            }
            catch (System.Exception ex)
            {
                result = ResponseResult.Error(ex.Message);
            }
            return(result);
        }
Esempio n. 27
0
        public async Task <ResponseResult> Add()
        {
            // 同步添加文档
            solr.Add(
                new PostDoc()
            {
                Id       = 30001,
                Name     = "This SolrNet Name",
                Title    = "This SolrNet Title",
                Excerpt  = "This SolrNet Excerpt",
                Content  = "This SolrNet Content 30001",
                PostDate = DateTime.Now
            }
                );
            // 异步添加文档
            await solr.AddAsync(
                new PostDoc()
            {
                Id       = 30002,
                Name     = "This SolrNet Name",
                Title    = "This SolrNet Title",
                Excerpt  = "This SolrNet Excerpt",
                Content  = "This SolrNet Content 30002",
                PostDate = DateTime.Now
            }
                );

            ResponseHeader responseHeader = await solr.CommitAsync();

            ResponseResult response = new ResponseResult();

            if (responseHeader.Status == 0)
            {
                response.Status = ResponseStatus.SUCCEED;
            }
            return(response);
        }
        public async Task <ResponseResult <ProductOrderEntity> > SyncOrder2()
        {
            var result = ResponseResult <ProductOrderEntity> .Default();

            using (IDbSession session = SessionFactory.CreateSession())
            {
                try
                {
                    session.BeginTrans();
                    var entity = ProductOrderService.SyncOrder(session.Connection, session.Transaction);
                    session.Commit();

                    //发布消息主题
                    var wfResult = PublishProductOrderCreateMessage(entity);
                    if (wfResult.Status == 1)
                    {
                        result = ResponseResult <ProductOrderEntity> .Success(entity,
                                                                              string.Format("同步订单数据状态:{0}", wfResult.Status));
                    }
                    else
                    {
                        session.Rollback();
                        result = ResponseResult <ProductOrderEntity> .Error(
                            string.Format("订单消息启动流程失败失败, 错误:{0}", wfResult.Message)
                            );
                    }
                }
                catch (System.Exception ex)
                {
                    session.Rollback();
                    result = ResponseResult <ProductOrderEntity> .Error(
                        string.Format("同步订单{0}失败, 错误:{1}", "ProductOrder", ex.Message)
                        );
                }
            }
            return(result);
        }
Esempio n. 29
0
        public ResponseResult ReverseProcess(WfAppRunner runner)
        {
            IWorkflowService wfService = new WorkflowService();
            IDbConnection    conn      = SessionFactory.CreateConnection();

            IDbTransaction trans = null;

            try
            {
                trans = conn.BeginTransaction();
                var result = wfService.ReverseProcess(conn, runner, trans);

                if (result.Status == WfExecutedStatus.Success)
                {
                    trans.Commit();
                    return(ResponseResult.Success());
                }
                else
                {
                    trans.Rollback();
                    return(ResponseResult.Error(result.Message));
                }
            }
            catch (WorkflowException w)
            {
                trans.Rollback();
                return(ResponseResult.Error(w.Message));
            }
            finally
            {
                trans.Dispose();
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Esempio n. 30
0
        public ResponseResult StartProcess([FromBody] WfAppRunner starter)
        {
            IWorkflowService wfService = new WorkflowService();
            IDbConnection    conn      = SessionFactory.CreateConnection();

            IDbTransaction trans = null;

            try
            {
                trans = conn.BeginTransaction();
                WfExecutedResult result = wfService.StartProcess(conn, starter, trans);
                trans.Commit();

                int newProcessInstanceID = result.ProcessInstanceIDStarted;
                if (result.Status == WfExecutedStatus.Success)
                {
                    return(ResponseResult.Success());
                }
                else
                {
                    return(ResponseResult.Error(result.Message));
                }
            }
            catch (WorkflowException w)
            {
                trans.Rollback();
                return(ResponseResult.Error(w.Message));
            }
            finally
            {
                trans.Dispose();
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }
        }
Esempio n. 31
0
        //Delete
        public static ResponseResult Delete(PeminjamanViewModel entity)
        {
            ResponseResult result = new ResponseResult();

            try
            {
                using (var db = new XContext())
                {
                    x_peminjaman peminjaman = db.x_peminjaman
                                              .Where(o => o.id == entity.Id)
                                              .FirstOrDefault();

                    if (peminjaman != null)
                    {
                        peminjaman.deleted_by = 1;
                        peminjaman.deleted_on = DateTime.Now;

                        peminjaman.is_delete = true;

                        db.SaveChanges();

                        result.Entity = entity;
                    }
                    else
                    {
                        result.Success = false;
                        result.Message = "Data Not Found ! ";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message;
            }
            return(result);
        }
Esempio n. 32
0
 public ResponseResult <string> delBook([FromQuery] string token, int id)
 {
     claim = (JwtClaim)_accessor.HttpContext.Items["user"];
     try
     {
         if (id == 0)
         {
             return(ResponseResult <string> .Error("参数异常"));
         }
         var b = SystemService.delBook(id, connstr);
         if (b)
         {
             return(ResponseResult <string> .Success("操作成功", "操作成功"));
         }
         else
         {
             return(ResponseResult <string> .Success("操作失败", "操作失败"));
         }
     }
     catch (Exception ex)
     {
         return(ResponseResult <string> .Error("系统异常"));
     }
 }
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //POST PUT 方法进行模型校验
            string method = context.HttpContext.Request.Method;

            if ((method == "POST" || method == "PUT") && !context.ModelState.IsValid)
            {
                //BindAttribute特性对JSON数据无效
                IList <ParameterDescriptor> parameterDescriptors = context.ActionDescriptor.Parameters;
                //获取BindAttribute
                ParameterDescriptor parameterDescriptor = parameterDescriptors.Where(item => item.BindingInfo.PropertyFilterProvider is BindAttribute).SingleOrDefault();

                BindAttribute bindAttribute = parameterDescriptor.BindingInfo.PropertyFilterProvider as BindAttribute;

                string message = context.ModelState.ToErrorMessageByBindAttribute(bindAttribute);

                if (message != string.Empty)
                {
                    ResponseResult responseResult = CommonFactory.CreateResponseResult;
                    context.Result = new JsonResult(responseResult.Failed(message));
                    return;
                }
            }
        }
        /// <summary>
        /// ニコニコ動画にログインする。
        /// </summary>
        /// <param name="userId">メールアドレス</param>
        /// <param name="password">パスワード</param>
        /// <returns></returns>
        public static ResponseResult Login(string userId, string password)
        {
            ResponseResult result = null;

            // 参考サイト:http://qiita.com/katabamisan/items/8028584b2b6224ce0c92
            string content = "mail=" + userId + "&password="******"POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = contentBytes.Length;

            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(contentBytes, 0, contentBytes.Length);
            }

            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch(WebException ex)
            {
                if(ex.Status == WebExceptionStatus.ProtocolError)
                {
                    return new ResponseResult(Constants.Result.ProtocolError, null);
                }

                return null;
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
                return null;
            }
            finally
            {

                if(response != null)
                {
                    Constants.Result r;
                    if(response.ResponseUri.AbsoluteUri.Contains("cant_login"))
                    {
                        r = Constants.Result.Failed;
                    }
                    else
                    {
                        r = Constants.Result.Success;
                    }

                    result = new ResponseResult(r, request.CookieContainer);
                    response.Close();
                }
            }

            return result;
        }
        /**
         *
         * method "POST" or "GET"
         * url
         * auth   可选
         */
        public ResponseResult sendRequest(String method, String url, String auth,String reqParams)
        {
            //Console.WriteLine("begin send" + reqParams);
            ResponseResult result = new ResponseResult();
            HttpWebRequest myReq = null;
            HttpWebResponse response = null;
            try
            {
                myReq = (HttpWebRequest)WebRequest.Create(url);
                myReq.Method = method;
                myReq.Accept = "text/html, application/xhtml+xml, */*";
                myReq.ContentType = "application/x-www-form-urlencoded";
                myReq.Headers.Add("Charset", "UTF-8");
                if ( !String.IsNullOrEmpty(auth) )
                {
                    myReq.Headers.Add("Authorization", "Basic " + auth);
                }

                if (method == "POST")
                {
                    byte[] bs = Encoding.ASCII.GetBytes(reqParams);
                    myReq.ContentLength = bs.Length;
                    using (Stream reqStream = myReq.GetRequestStream())
                    {
                        reqStream.Write(bs, 0, bs.Length);
                        reqStream.Close();
                    }
                }
               // Console.WriteLine("begin responese");

                response = (HttpWebResponse)myReq.GetResponse();
                HttpStatusCode statusCode = response.StatusCode;
                result.responseCode = statusCode;
                //    Console.WriteLine("prepare");
                if (Equals(response.StatusCode, HttpStatusCode.OK))
                {
                    //Console.WriteLine("enter");
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                    {
                        result.responseContent = reader.ReadToEnd();
                       // Console.WriteLine(result.responseContent);
                    }
                    result.setErrorObject();
                }
                    //Console.WriteLine("end");
                //Console.WriteLine("response = " + response.Headers + "  contet=" + result.responseContent + "   status=" + response.StatusCode);
                //Console.WriteLine("remaining = " + remaining);
               // Console.WriteLine("code = " + result.error.errcode);

                if (statusCode == HttpStatusCode.OK)
                {
                    String limitQuota = response.GetResponseHeader(RATE_LIMIT_QUOTA);
                    String limitRemaining = response.GetResponseHeader(RATE_LIMIT_Remaining);
                    String limitReset = response.GetResponseHeader(RATE_LIMIT_Reset);
                    result.setRateLimit(limitQuota, limitRemaining, limitReset);
                    //Console.WriteLine("send success  ");
                }
                else if (statusCode == HttpStatusCode.NotFound)
                {
                    Debug.Print("error is 404");
                }
                else if (statusCode == HttpStatusCode.Forbidden)
                {
                    Debug.Print("error is 403");
                }
                else if (statusCode == HttpStatusCode.Unauthorized)
                {
                    Debug.Print("error is 401");
                }
                else if (statusCode == HttpStatusCode.InternalServerError)
                {
                    Debug.Print("error is 500");
                }
                else
                {
                    Debug.Print("error is " + statusCode.ToString());
                }

            }
            catch (System.Exception ex)
            {
                String errorMsg = ex.Message;
                Debug.Print(errorMsg);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }

                if(myReq != null)
                {
                    myReq.Abort();
                }
            }
            //Console.WriteLine("sssssssssssssss======="+result.responseCode);
            return result;
        }