コード例 #1
0
        public async Task<IServiceResult> CreateSpentTime(SpentTimeEditViewModel model)
        {
            var result = new ServiceResult<SpentTimeEditViewModel>();

            try
            {
                var user = await userManager.FindByIdAsync(model.UserId);
                if(user == null)
                {
                    result.AddError("", "Ez a felhasználó nem létezik");
                }

                var issue = await context.Issues.FindAsync(model.IssueId);
                if(issue == null)
                {
                    result.AddError(m => m.IssueId, "Ez a feladat nem létezik");
                }

                if(result.Succeeded)
                {
                    var spentTime = mapper.Map<SpentTime>(model);
                    spentTime.User = user;
                    spentTime.Issue = issue;

                    context.SpentTimes.Add(spentTime);
                    await context.SaveChangesAsync();
                }
            }
            catch (Exception e)
            {
                result.AddError("", e.Message);
            }

            return result;
        }
コード例 #2
0
        public ServiceResult<IPropertyTag> AddPropertyTag(string pin, string name)
        {
            ServiceResult<IPropertyTag> retVal = new ServiceResult<IPropertyTag>();
            FVCP.Persistence.EF.PropertyTag dbItem = null;
            using (var db = new PropertyEntities())
            {
                dbItem = db.PropertyTags
                    .FirstOrDefault(x => x.Pin == pin && x.Name == name);

                if (dbItem == null)
                {   // Go ahead and add the item, it isn't a duplicate.
                    dbItem = new EF.PropertyTag()
                    {
                        Name = name,
                        Pin = pin
                    };

                    db.PropertyTags.Add(dbItem);
                    db.SaveChanges();  // ID value should populate.

                    PropertyTagDTO dto = PropertyTagRepository.MapFieldValues(dbItem);
                    PropertyTagFactory myFact = new PropertyTagFactory();
                    retVal.Data = myFact.Create(dto);
                    retVal.Success = true;
                }
                else
                {
                    retVal.Success = false;
                    retVal.ErrorID = "422";
                    retVal.Message = string.Format("Unprocessable Entity - Tag '{0}' already exists for PIN '{1}'", name, pin);
                }
            }

            return retVal;
        }
コード例 #3
0
ファイル: MemberController.cs プロジェクト: navy235/7980Site
 public ActionResult Create(DetailsViewModel model)
 {
     var groups = GetForeignData();
     ViewBag.Data_GroupID = groups;
     ServiceResult result = new ServiceResult();
     TempData["Service_Result"] = result;
     if (ModelState.IsValid)
     {
         try
         {
             MemberService.Create(model);
             result.Message = "添加会员信息成功!";
             LogHelper.WriteLog("添加会员信息成功");
             return RedirectToAction("index");
         }
         catch (Exception ex)
         {
             result.Message = Utilities.GetInnerMostException(ex);
             result.AddServiceError(result.Message);
             LogHelper.WriteLog("添加会员信息错误", ex);
             return View(model);
         }
     }
     else
     {
         result.Message = "请检查表单是否填写完整!";
         result.AddServiceError("请检查表单是否填写完整!");
         return View(model);
     }
 }
コード例 #4
0
        public async Task<IServiceResult> CreateProject(ProjectEditViewModel model)
        {
            var result = new ServiceResult<ProjectEditViewModel>();

            try
            {
                var responsible = await userManager.FindByIdAsync(model.ResponsibleUserId);
                if(responsible == null)
                {
                    result.AddError(m => m.ResponsibleUserId, "Ilyen felhasználó nem létezik");
                }

                if(result.Succeeded)
                {
                    var project = mapper.Map<Project>(model);
                    project.Responsible = responsible;

                    context.Projects.Add(project);
                    await context.SaveChangesAsync();
                }
            }
            catch (Exception e)
            {
                result.AddError("", e.Message);
            }

            return result;
        }
コード例 #5
0
ファイル: AlbumForm.cs プロジェクト: anujahuja/hyvesfotos
        public void AlbumCallback(ServiceResult<Album> serviceResult)
        {
            // Adding Dir to control;
            this.Invoke((HyvesServicesCallback<Album>)delegate(ServiceResult<Album> result) { AddAlbumInListView(result.Result); }, serviceResult);

            List<string> files = new List<string>();
            foreach (FileInfo file in this.uploadDirectory.GetFiles())
            {
                files.Add(file.FullName);
            }

            if (files.Count == 0)
            {
                return;
            }

            // uploading files
            this.Invoke((HyvesServicesCallback<Album>)delegate(ServiceResult<Album> result)
            {
                lvMedia.Tag = result.Result;
                HyvesBatchUploadRequest hyvesBatchUploadRequest = MediaService.UploadFiles(files, result.Result, new HyvesServicesCallback<HyvesBatchUploadRequest>(HyvesBatchUploadCallback));
                hyvesBatchUploadRequest.OnBatchUploadProgressChanged += new HyvesServicesCallback<int>(hyvesBatchUploadRequest_OnBatchUploadProgressChanged);
                uploadProgress.Completed = 0;
                uploadProgress.Total = files.Count;
                uploadProgress.ShowDialog();
            }, serviceResult);
        }
コード例 #6
0
		public ServiceResult<Category> AddCategory(string name, int? categoryGroupId = null)
		{
			var result = new ServiceResult<Category>();

			// does Category Group exist?
			if (categoryGroupId.HasValue)
			{
				var categoryGroupResult = GetCategoryGroup(categoryGroupId.Value);
				if (categoryGroupResult.HasErrors)
				{
					result.AddErrors(categoryGroupResult);
					return result;
				}
			}

			// create Category
			var category = new Category()
			{
				Name = name,
				CategoryGroupId = categoryGroupId,
			};

			_db.Insert<Category>(category);

			result.Result = category;
			return result;
		}
コード例 #7
0
        public async Task<IServiceResult> CreateIssue(IssueEditViewModel model)
        {
            var result = new ServiceResult<IssueEditViewModel>();

            try
            {
                var project = await context.Projects.FindAsync(model.ProjectId);
                if(project == null)
                {
                    result.AddError(m => m.ProjectId, "Ilyen projekt nem létezik");
                    return result;
                }

                var issue = mapper.Map<Issue>(model);
                issue.Project = project;
                issue.State = IssueState.New;
                context.Issues.Add(issue);

                await context.SaveChangesAsync(); 

            }
            catch (Exception e)
            {
                result.AddError("", e.Message);
            }

            return result;
        }
コード例 #8
0
        public async Task<ServiceResult> ChangeState(int issueId, IssueState newState)
        {
            var result = new ServiceResult();

            try
            {
                //franc se tudja miért, de ha nincs ráincludeolva a project, elszáll a required miatt...
                var issue = await context.Issues.Include(i => i.Project).SingleOrDefaultAsync(i => i.Id == issueId);
                if (issue == null)
                {
                    result.AddError("", "Nincs ilyen azonosítójú feladat.");
                    return result;
                }

                issue.State = newState;
                await context.SaveChangesAsync();

            }
            catch (Exception e)
            {
                result.AddError("", e.Message);
            }

            return result;
        }
コード例 #9
0
        public ServiceResult<IPropertyTag> UpdatePropertyTag(int id, string name)
        {
            ServiceResult<IPropertyTag> retVal = new ServiceResult<IPropertyTag>();
            FVCP.Persistence.EF.PropertyTag dbItem = null;
            using (var db = new PropertyEntities())
            {
                dbItem = db.PropertyTags
                    .FirstOrDefault(x => x.Id == id);

                if (dbItem != null)
                {
                    dbItem.Name = name;
                    db.SaveChanges();

                    PropertyTagFactory myFact = new PropertyTagFactory();
                    retVal.Data = myFact.Create(GetPropertyTagById(id).Data);
                    retVal.Success = true;
                }
                else
                {   // Item doesn't exist.
                    retVal.Success = false;
                    retVal.ErrorID = "404";
                    retVal.Message = string.Format("Tag id '{0}' was not found.  Unable to update property tag '{1}'.",
                        id, name);
                }
            }

            return retVal;
        }
コード例 #10
0
        public async Task<IServiceResult> CreateProjectVersion(ProjectVersionEditViewModel model)
        {
            var result = new ServiceResult<ProjectVersionEditViewModel>();

            try
            {
                var project = await ProjectStore.GetAll().Include(p => p.Versions).SingleOrDefaultAsync(p => p.Id == model.ProjectId);
                if (project == null)
                {
                    result.AddError(m => m.ProjectId, "Ilyen azonosítóval nem létezik projekt!");
                    return result;
                }
                
                var version = Mapper.Map<ProjectVersionEditViewModel, ProjectVersion>(model);
                version.Project = project;

                await ProjectVersionStore.InsertAsync(version);
            }
            catch (Exception e)
            {
                Log.Error(e.Message, e);

                result.AddError("", e.Message);
            }

            return result;
        }
コード例 #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ServiceResponse"/> class.
 /// </summary>
 /// <param name="soapFaultDetails">The SOAP fault details.</param>
 internal ServiceResponse(SoapFaultDetails soapFaultDetails)
 {
     this.result = ServiceResult.Error;
     this.errorCode = soapFaultDetails.ResponseCode;
     this.errorMessage = soapFaultDetails.FaultString;
     this.errorDetails = soapFaultDetails.ErrorDetails;
 }
コード例 #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ServiceResponse"/> class.
 /// This is intended to be used by unit tests to create a fake service error response
 /// </summary>
 /// <param name="responseCode">Response code</param>
 /// <param name="errorMessage">Detailed error message</param>
 internal ServiceResponse(ServiceError responseCode, string errorMessage)
 {
     this.result = ServiceResult.Error;
     this.errorCode = responseCode;
     this.errorMessage = errorMessage;
     this.errorDetails = null;
 }
コード例 #13
0
ファイル: VendorService.cs プロジェクト: kenwarner/scrilla.js
		public ServiceResult<Vendor> AddVendor(string name, int? defaultCategoryId = null)
		{
			var result = new ServiceResult<Vendor>();

			// TODO do we need to handle a case where defaultCategoryId = 0
			//if (defaultCategoryId.HasValue && defaultCategoryId.Value == 0)
			//	defaultCategoryId = null;


			// does category exist?
			if (defaultCategoryId.HasValue)
			{
				var categoryResult = _categoryService.GetCategory(defaultCategoryId.Value);
				if (categoryResult.HasErrors)
				{
					result.AddErrors(categoryResult);
					return result;
				}
			}

			// create Vendor
			var vendor = new Vendor()
			{
				Name = name,
				DefaultCategoryId = defaultCategoryId
			};

			_db.Insert<Vendor>(vendor);

			result.Result = vendor;
			return result;
		}
コード例 #14
0
ファイル: LoginForm.cs プロジェクト: hyvesfun/jenna
 private void AccessTokenCallback(ServiceResult<AccessToken> serviceResult)
 {
     HyvesApplication hyvesApplication = HyvesApplication.GetInstance();
     hyvesApplication.AccessToken = serviceResult.Result.oauth_token;
     hyvesApplication.AccessTokenSecret = serviceResult.Result.oauth_token_secret;
     hyvesApplication.UserId = serviceResult.Result.userid;
     this.DialogResult = System.Windows.Forms.DialogResult.OK;
 }
コード例 #15
0
ファイル: LoginForm.cs プロジェクト: hyvesfun/jenna
        private void RequestTokenCallback(ServiceResult<RequestToken> serviceResult)
        {
            StartLoginDelegate startLoginDelegate = new StartLoginDelegate(StartLogin);
            HyvesApplication hyvesApplication = HyvesApplication.GetInstance();
            hyvesApplication.RequestToken = serviceResult.Result.oauth_token;
            hyvesApplication.RequestTokenSecret = serviceResult.Result.oauth_token_secret;

            // Showing LoginForm to user
            this.BeginInvoke(startLoginDelegate, serviceResult.Result.oauth_token);
        }
コード例 #16
0
ファイル: AuthService.cs プロジェクト: hyvesfun/jenna
 private static void AccessTokenResponseCallback(RequestResult<AccessToken> requestResult)
 {
     ServiceResult<AccessToken> serviceResult = new ServiceResult<AccessToken>() { IsError = requestResult.IsError, Execption = requestResult.Execption, Message = requestResult.Message };
     if (!requestResult.IsError)
     {
         AccessToken requestToken = JsonConvert.DeserializeObject<AccessToken>(requestResult.Response);
         serviceResult.Result = requestToken;
     }
     requestResult.Callback(serviceResult);
 }
コード例 #17
0
ファイル: UserService.cs プロジェクト: hyvesfun/jenna
 private static void UsersGetByFriendsLastLoginReponseCallback(RequestResult<List<User>> requestResult)
 {
     ServiceResult<List<User>> serviceResult = new ServiceResult<List<User>>() { IsError = requestResult.IsError, Execption = requestResult.Execption, Message = requestResult.Message };
     if (!requestResult.IsError)
     {
         UsersGetByFriendsLastLoginResponse usersGetByFriendsLastLoginResponse = JsonConvert.DeserializeObject<UsersGetByFriendsLastLoginResponse>(requestResult.Response);
         serviceResult.Result = usersGetByFriendsLastLoginResponse.user;
     }
     requestResult.Callback(serviceResult);
 }
コード例 #18
0
        public IHttpActionResult GetProduct(Guid id)
        {
            var productResult = Business.GetProduct(id);

            var result = new ServiceResult<ProductDTO>
            {
                StatusCode = HttpStatusCode.OK,
                Data = productResult,
                Success = true
            };
            return Ok(result);
        }
コード例 #19
0
        public IHttpActionResult ListProducts()
        {
            var productResult = Business.ListProducts();

            var result = new ServiceResult<IList<ProductDTO>>
            {
                StatusCode = HttpStatusCode.OK,
                Data = productResult,
                Success = true
            };
            return Ok(result);
        }
コード例 #20
0
ファイル: LoginForm.cs プロジェクト: anujahuja/hyvesfotos
 private void UpdateAfterLogin(ServiceResult<bool> serviceResult)
 {
     this.Cursor = Cursors.Default;
     if (serviceResult.IsError)
     {
         MessageBox.Show(Util.LocalizedText("LoginFail"), "Hyves Fotos", MessageBoxButtons.OK);
         return;
     }
     this.DialogResult = System.Windows.Forms.DialogResult.OK;
     AlbumForm showAlbum = new AlbumForm();
     showAlbum.Show();
     this.Hide();
 }
コード例 #21
0
        public IHttpActionResult CreateProduct(ProductDTO product)
        {
            if (!ModelState.IsValid)
                return BadRequest("Invalid data");

            var productResult = Business.CreateProduct(product);

            var result = new ServiceResult<ProductDTO>
            {
                StatusCode = HttpStatusCode.OK,
                Data = productResult,
                Success = true
            };
            return Ok(result);
        }
コード例 #22
0
        public override ServiceResult<Order> Update(Order order)
        {
            var result = new ServiceResult<Order>();

            if (ThrowError)
            {
                result.AddModelError("", "Fake Error");
            }
            else
            {
                result.Entity = order;
                result.Entity.OrderId = 1;
            }

            return result;
        }
コード例 #23
0
        /// <summary>
        /// Készít egy új platformot
        /// </summary>
        /// <param name="model">Az új platform modelje</param>
        /// <returns></returns>
        public async Task<IServiceResult> CreatePlatform(PlatformEditViewModel model)
        {
            var result = new ServiceResult<PlatformEditViewModel>();

            try
            {
                await TestPlatformStore.InsertAsync(Mapper.Map<PlatformEditViewModel, Platform>(model));
            }
            catch (Exception e)
            {
                Log.Error(e.Message, e);

                result.AddError("", e.Message);
            }

            return result;
        }
コード例 #24
0
ファイル: LoginNoPopup.cs プロジェクト: hyvesfun/jenna
        public void RequestTokenCallback(ServiceResult<RequestToken> serviceResult)
        {
            if (serviceResult.IsError)
            {
                ServiceResult<bool> result = new ServiceResult<bool>() { IsError = serviceResult.IsError, Execption = serviceResult.Execption, Message = serviceResult.Message };
                result.Result = false;
                loginCallbackDelegate(result);
                return;
            }

            HyvesApplication hyvesApplication = HyvesApplication.GetInstance();
            hyvesApplication.RequestToken = serviceResult.Result.oauth_token;
            hyvesApplication.RequestTokenSecret = serviceResult.Result.oauth_token_secret;

            // Getting Access token
            AuthService.AccessToken(new HyvesServicesCallback<AccessToken>(AccessTokenCallback));
        }
コード例 #25
0
        public async Task<IServiceResult> UpdateProjectVersion(ProjectVersionEditViewModel model)
        {
            var result = new ServiceResult<ProjectVersionEditViewModel>();

            try
            {
                await ProjectVersionStore.UpdateAsync(Mapper.Map<ProjectVersionEditViewModel, ProjectVersion>(model));
            }
            catch (Exception e)
            {
                Log.Error(e.Message, e);

                result.AddError("", e.Message);
            }

            return result;
        }
コード例 #26
0
        public ServiceResult<ImageModel> Get(string url)
        {
            var result = new ServiceResult<ImageModel>() { Result = new ImageModel() };

            try
            {
                var webClient = new WebClient();
                result.Result.Extension = Path.GetExtension(url).Substring(1);
                var image = webClient.DownloadData(url);
                result.Result.Image64String = Convert.ToBase64String(image);
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
コード例 #27
0
ファイル: BillService.cs プロジェクト: kenwarner/scrilla.js
		/// <summary>
		/// Returns a list of bill transactions scheduled for this bill during this timeframe
		/// </summary>
		/// <param name="billId">Get all bill transactions for a value of null</param>
		/// <param name="from"></param>
		/// <param name="to"></param>
		/// <returns></returns>
		public ServiceResult<IEnumerable<BillTransaction>> GetBillTransactions(int? billId, DateTime? from = null, DateTime? to = null)
		{
			var result = new ServiceResult<IEnumerable<BillTransaction>>();

			var predicates = new List<IPredicate>();

			if (billId.HasValue)
				predicates.Add(Predicates.Field<BillTransaction>(x => x.BillId, Operator.Eq, billId.Value));
			if (from.HasValue)
				predicates.Add(Predicates.Field<BillTransaction>(x => x.Timestamp, Operator.Ge, from.Value));
			if (to.HasValue)
				predicates.Add(Predicates.Field<BillTransaction>(x => x.Timestamp, Operator.Le, to.Value));

			var predicate = new PredicateGroup { Operator = GroupOperator.And, Predicates = predicates };
			var billTransactions = _db.GetList<BillTransaction>(predicate);

			result.Result = billTransactions;
			return result;
		}
コード例 #28
0
ファイル: UserService.cs プロジェクト: PQ4NOEH/.NET-recipes
 public ServiceResult<User> Login(NotNullable<UserCredentials> credentials)
 {
     ServiceResult<User>  result = null;
     var validation = _credentialValidator.Validate(credentials);
     if(validation.IsValid)
     {
         var user = _userRepository.LoadUser(credentials.Value.UserMail);
         if(user.Password.Equals(_hashGenerator.GenerateHash(credentials.Value.Password)))
         {
             result = new ServiceResult<User>(user);
         }
         else result = new ServiceResult<User>(new IServiceError[] { new UserOrPasswordDoesNotMatch() });
     }
     else
     {
         result = new ServiceResult<User>(validation.Errors.Select(v => v.CustomState as IServiceError));
     }
     return result;
 }
コード例 #29
0
ファイル: LoginNoPopup.cs プロジェクト: hyvesfun/jenna
        private void AccessTokenCallback(ServiceResult<AccessToken> serviceResult)
        {
            ServiceResult<bool> result = new ServiceResult<bool>() { IsError = serviceResult.IsError, Execption = serviceResult.Execption, Message = serviceResult.Message };
            if (serviceResult.IsError)
            {
                result.Result = false;
                loginCallbackDelegate(result);
                return;
            }

            HyvesApplication hyvesApplication = HyvesApplication.GetInstance();
            hyvesApplication.AccessToken = serviceResult.Result.oauth_token;
            hyvesApplication.AccessTokenSecret = serviceResult.Result.oauth_token_secret;
            hyvesApplication.UserId = serviceResult.Result.userid;

            result.Result = true;
            // Letting user interface know
            loginCallbackDelegate(result);
        }
コード例 #30
0
		public ServiceResult<Account> AddAccount(string name, decimal initialBalance = 0.0M, int? defaultCategoryId = null, int? accountGroupId = null)
		{
			var result = new ServiceResult<Account>();

			// does AccountGroup exist?
			if (accountGroupId.HasValue)
			{
				var accountGroupResult = GetAccountGroup(accountGroupId.Value);
				if (accountGroupResult.HasErrors)
				{
					result.AddErrors(accountGroupResult);
					return result;
				}
			}

			// does default Category exist?
			if (defaultCategoryId.HasValue)
			{
				var categoryResult = _categoryService.GetCategory(defaultCategoryId.Value);
				if (categoryResult.HasErrors)
				{
					result.AddErrors(categoryResult);
					return result;
				}
			}

			// create Account
			var account = new Account()
			{
				Name = name,
				InitialBalance = initialBalance,
				Balance = initialBalance,
				BalanceTimestamp = DateTime.Now,
				DefaultCategoryId = defaultCategoryId,
				AccountGroupId = accountGroupId
			};

			_db.Insert<Account>(account);

			result.Result = account;
			return result;
		}
コード例 #31
0
        /// <summary>
        /// Publishes a value.
        /// </summary>
        private void Publish(
            OperationContext context,
            DataValue value,
            ServiceResult error,
            Queue <MonitoredItemNotification> notifications,
            Queue <DiagnosticInfo> diagnostics)
        {
            // set semantics changed bit.
            if (m_semanticsChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetSemanticsChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetSemanticsChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_semanticsChanged = false;
            }

            // set structure changed bit.
            if (m_structureChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetStructureChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetStructureChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_structureChanged = false;
            }

            // copy data value.
            MonitoredItemNotification item = new MonitoredItemNotification();

            item.ClientHandle = m_clientHandle;
            item.Value        = value;

            // apply timestamp filter.
            if (m_timestampsToReturn != TimestampsToReturn.Server && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.ServerTimestamp = DateTime.MinValue;
            }

            if (m_timestampsToReturn != TimestampsToReturn.Source && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.SourceTimestamp = DateTime.MinValue;
            }

            notifications.Enqueue(item);

            // update diagnostic info.
            DiagnosticInfo diagnosticInfo = null;

            if (m_lastError != null)
            {
                if ((m_diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0)
                {
                    diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_source.Server, context, m_lastError);
                }
            }

            diagnostics.Enqueue(diagnosticInfo);
        }
コード例 #32
0
ファイル: UserRightsService.cs プロジェクト: adteven/alabo
        /// <summary>
        ///     商家服务订购
        /// </summary>
        /// <param name="orderBuyInput"></param>
        /// <returns></returns>
        public async Task <Tuple <ServiceResult, OrderBuyOutput> > Buy(UserRightsOrderInput orderBuyInput)
        {
            #region 安全验证

            var result         = ServiceResult.Success;
            var orderBuyOutput = new OrderBuyOutput();
            var user           = Resolve <IUserService>().GetNomarlUser(orderBuyInput.UserId);
            if (user == null)
            {
                return(Tuple.Create(ServiceResult.Failure("用户不存在,或状态不正常"), orderBuyOutput));
            }

            orderBuyInput.BuyUser = user; // 购买用户等于当前用户

            user.Detail = null;           // 减少体积保存
            user.Map    = null;
            if (orderBuyInput.GradeId.IsGuidNullOrEmpty())
            {
                return(Tuple.Create(ServiceResult.Failure("等级Id不能为空"), orderBuyOutput));
            }

            orderBuyInput.User = user;
            var userGrades = Resolve <IAutoConfigService>().GetList <UserGradeConfig>();
            var buyGrade   = userGrades.FirstOrDefault(r => r.Id == orderBuyInput.GradeId);
            if (buyGrade == null)
            {
                return(Tuple.Create(ServiceResult.Failure("购买的等级不存在"), orderBuyOutput));
            }

            var userRightConfig = Resolve <IAutoConfigService>().GetList <UserRightsConfig>()
                                  .FirstOrDefault(c => c.GradeId == buyGrade.Id);
            if (userRightConfig != null && !userRightConfig.IsOpen)
            {
                return(Tuple.Create(ServiceResult.Failure("该等级暂未开放"), orderBuyOutput));
            }

            orderBuyInput.BuyGrade     = buyGrade;
            orderBuyInput.CurrentGrade = userGrades.FirstOrDefault(r => r.Id == user.GradeId);
            if (orderBuyInput.CurrentGrade == null)
            {
                return(Tuple.Create(ServiceResult.Failure("您的等级不存在"), orderBuyOutput));
            }

            // 准营销中心,和营销中心的开通只能是管理员 动态配置,不用写死
            //if (orderBuyInput.GradeId == Guid.Parse("f2b8d961-3fec-462d-91e8-d381488ea972") || orderBuyInput.GradeId == Guid.Parse("cc873faa-749b-449b-b85a-c7d26f626feb"))
            //{
            if (orderBuyInput.OpenType == UserRightOpenType.AdminOpenHightGrade)
            {
                if (!Resolve <IUserService>().IsAdmin(user.Id))
                {
                    return(Tuple.Create(ServiceResult.Failure("您不是管理员无权开通"), orderBuyOutput));
                }

                if (orderBuyInput.Parent.IsNullOrEmpty())
                {
                    return(Tuple.Create(ServiceResult.Failure("推荐人不能为空"), orderBuyOutput));
                }

                orderBuyInput.ParnetUser = Resolve <IUserService>().GetSingleByUserNameOrMobile(orderBuyInput.Parent);
                if (orderBuyInput.ParnetUser == null)
                {
                    return(Tuple.Create(ServiceResult.Failure("推荐人不能为空,不能开通营销中心"), orderBuyOutput));
                }
            }
            //}

            if (orderBuyInput.OpenType == UserRightOpenType.OpenToOtherByPay ||
                orderBuyInput.OpenType == UserRightOpenType.AdminOpenHightGrade ||
                orderBuyInput.OpenType == UserRightOpenType.OpenToOtherByRight)
            {
                if (orderBuyInput.Mobile.IsNullOrEmpty())
                {
                    return(Tuple.Create(ServiceResult.Failure("请输入手机号码"), orderBuyOutput));
                }

                if (orderBuyInput.Name.IsNullOrEmpty())
                {
                    return(Tuple.Create(ServiceResult.Failure("请输入公司名称或姓名"), orderBuyOutput));
                }

                // 查找是否为注册用户
                var find = Resolve <IUserService>().GetSingleByUserNameOrMobile(orderBuyInput.Mobile);
                if (find != null)
                {
                    var findUserGrade = userGrades.FirstOrDefault(r => r.Id == find.GradeId);
                    if (findUserGrade == null)
                    {
                        return(Tuple.Create(ServiceResult.Failure("激活的用户等级不存在"), orderBuyOutput));
                    }

                    if (findUserGrade.Price > 0.01m)
                    {
                        return(Tuple.Create(ServiceResult.Failure("该用户已激活"), orderBuyOutput));
                    }

                    //var records = Resolve<IRecordService>().GetListNoTracking(s => s.Type == typeof(UserDetail).FullName);
                    //var findRecord = records.FirstOrDefault(s => s.UserId == user.Id);
                    //var findUser = findRecord?.Value?.ToObject<RegInput>();
                    //if (findUser != null)
                    //    orderBuyInput.RegInfo = findUser;
                    //else
                    //{
                    orderBuyInput.RegInfo = new RegInput {
                        Mobile      = find.Mobile,
                        UserName    = find.Mobile,
                        Name        = find.Name,
                        Password    = "******",
                        PayPassword = "******",
                        ParentId    = find.ParentId
                    };
                    // }
                }
                else
                {
                    if (!RegexHelper.CheckMobile(orderBuyInput.Mobile))
                    {
                        return(Tuple.Create(ServiceResult.Failure("手机号码格式不正确"), orderBuyOutput));
                    }
                    // 注册新用户
                    var password    = RandomHelper.PassWord();
                    var payPassword = RandomHelper.PayPassWord();
                    var regInput    = new RegInput {
                        Mobile      = orderBuyInput.Mobile,
                        UserName    = orderBuyInput.Mobile,
                        Name        = orderBuyInput.Name,
                        Password    = password,
                        PayPassword = payPassword,
                        ParentId    = orderBuyInput.UserId
                    };
                    orderBuyInput.RegInfo = regInput;
                    // 如果是管理员,则推荐人Id改为输入的推荐人Id
                    if (orderBuyInput.OpenType == UserRightOpenType.AdminOpenHightGrade)
                    {
                        regInput.ParentId = orderBuyInput.ParnetUser.Id;
                    }
                    //
                    var userRegResult = Resolve <IUserBaseService>().Reg(regInput);
                    if (!userRegResult.Item1.Succeeded)
                    {
                        return(Tuple.Create(ServiceResult.Failure("新会员注册失败" + userRegResult),
                                            orderBuyOutput));
                    }
                    // await Resolve<IRecordService>().AddAsync(new Record() { Type = typeof(UserDetail).FullName, Value = regInput.ToJsons() });

                    find = Resolve <IUserService>().GetSingle(orderBuyInput.Mobile);

                    var message =
                        $"恭喜您,您的账号已注册成功。您的登录账号为:{regInput.Mobile},初始登录密码:{password} 初始支付密码:{payPassword} 请妥善保管.";
                    Resolve <ISmsService>().SendRaw(find.Mobile, message);

                    message =
                        $"您推荐的商家已注册成功.登录账号:{regInput.Mobile},初始登录密码:{password} 初始支付密码:{payPassword} 请尽快让商家悉知,第一时间指导商家使用系统.";

                    var userDetail = Resolve <IUserDetailService>().GetSingle(u => u.UserId == user.Id);
                    userDetail.RegionId = orderBuyInput.RegionId.ToInt64();
                    Resolve <IUserDetailService>().Update(userDetail);
                    Resolve <ISmsService>().SendRaw(user.Mobile, message);
                }

                orderBuyInput.BuyUser = find;
            }

            #endregion 安全验证

            orderBuyInput.UserRightList = GetList(r => r.UserId == user.Id);

            // 如果是帮别人开通
            if (orderBuyInput.OpenType == UserRightOpenType.OpenToOtherByRight)
            {
                return(await OpenToOther(orderBuyInput));
            }

            // 其他三种情况都需要支付 +或者管理员帮他们开通
            return(await OpenSelfOrUpgrade(orderBuyInput));
        }
コード例 #33
0
ファイル: OutDoorController.cs プロジェクト: navy235/7980Site
        public ActionResult Edit(OutDoorViewModel model)
        {
            ViewBag.MenuItem = "media-list";
            if (!CheckMemberStatus())
            {
                return(Redirect(Url.Action("openbiz", "register")));
            }

            ServiceResult result = new ServiceResult();

            TempData["Service_Result"] = result;
            var AreaCateArray     = new List <int>();
            var CrowdCateArray    = new List <int>();
            var IndustryCateArray = new List <int>();
            var PurposeCateArray  = new List <int>();

            //if (!string.IsNullOrEmpty(model.AreaCate))
            //{
            //    AreaCateArray = model.AreaCate.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            //}
            //if (!string.IsNullOrEmpty(model.CrowdCate))
            //{
            //    CrowdCateArray = model.CrowdCate.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            //}
            //if (!string.IsNullOrEmpty(model.IndustryCate))
            //{
            //    IndustryCateArray = model.IndustryCate.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            //}

            //if (!string.IsNullOrEmpty(model.PurposeCate))
            //{
            //    PurposeCateArray = model.PurposeCate.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            //}

            if (!ModelState.IsValid)
            {
                result.Message = "表单输入有误,请仔细填写表单!";
                result.AddServiceError("表单输入有误,请仔细填写表单!");
            }
            else
            {
                try
                {
                    OutDoorService.Update(model);
                    result.Message = "编辑户外成功!";
                    return(RedirectToAction("preverify"));
                }
                catch (Exception ex)
                {
                    result.Message = "编辑户外失败!";
                    result.AddServiceError(Utilities.GetInnerMostException(ex));
                    LogHelper.WriteLog("用户:" + CookieHelper.MemberID + "编辑户外失败!", ex);
                }
            }
            //ViewBag.Data_CrowdCate = Utilities.GetSelectListData(CrowdCateService.GetALL(), x => x.ID, x => x.CateName, CrowdCateArray, false);
            //ViewBag.Data_IndustryCate = Utilities.GetSelectListData(IndustryCateService.GetALL(), x => x.ID, x => x.CateName, IndustryCateArray, false);
            //ViewBag.Data_PurposeCate = Utilities.GetSelectListData(PurposeCateService.GetALL(), x => x.ID, x => x.CateName, PurposeCateArray, false);
            //ViewBag.Data_AreaCate = Utilities.GetSelectListData(AreaCateService.GetALL(), x => x.ID, x => x.CateName, AreaCateArray, false);
            ViewBag.Data_FormatCode = Utilities.GetSelectListData(FormatCateService.GetALL(), x => x.ID, x => x.CateName, true);
            ViewBag.Data_PeriodCode = Utilities.GetSelectListData(PeriodCateService.GetALL(), x => x.ID, x => x.CateName, true);
            //ViewBag.Data_OwnerCode = Utilities.GetSelectListData(OwnerCateService.GetALL(), x => x.ID, x => x.CateName, false);
            return(View(model));
        }
コード例 #34
0
        /// <summary>
        /// Process received buffer
        /// </summary>
        private ServiceResult ProcessReceivedBuffer(int bytesRead)
        {
            // complete operation.
            BufferManager.UnlockBuffer(_receiveBuffer);
            Utils.TraceDebug("Bytes read: {0}", bytesRead);
            if (bytesRead == 0)
            {
                // Remote end has closed the connection
                // free the empty receive buffer.
                if (_receiveBuffer != null)
                {
                    _bufferManager.ReturnBuffer(_receiveBuffer,
                                                nameof(ProcessReceivedBuffer));
                    _receiveBuffer = null;
                }
                return(ServiceResult.Create(StatusCodes.BadConnectionClosed,
                                            "Remote side closed connection"));
            }

            _bytesReceived += bytesRead;
            // check if more data left to read.
            if (_bytesReceived < _bytesToReceive)
            {
                BeginReceive();
                return(ServiceResult.Good);
            }
            // start reading the message body.
            if (_incomingMessageSize < 0)
            {
                _incomingMessageSize = BitConverter.ToInt32(_receiveBuffer, 4);
                if (_incomingMessageSize <= 0 ||
                    _incomingMessageSize > _receiveBufferSize)
                {
                    Utils.Trace($"BadTcpMessageTooLarge: BufferSize={_receiveBufferSize}; " +
                                $"MessageSize={_incomingMessageSize}");
                    return(ServiceResult.Create(StatusCodes.BadTcpMessageTooLarge,
                                                "Messages size {1} bytes is too large for buffer of size {0}.",
                                                _receiveBufferSize, _incomingMessageSize));
                }
                // set up buffer for reading the message body.
                _bytesToReceive = _incomingMessageSize;
                BeginReceive();
                return(ServiceResult.Good);
            }

            // notify the sink.
            lock (_sinkLock) {
                if (_sink != null)
                {
                    try {
                        var messageChunk = new ArraySegment <byte>(_receiveBuffer, 0,
                                                                   _incomingMessageSize);
                        // Do not free the receive buffer now, it is freed in the stack.
                        _receiveBuffer = null;
                        // send notification
                        _sink.OnMessageReceived(this, messageChunk);
                    }
                    catch (Exception ex) {
                        Utils.Trace(ex,
                                    "Unexpected error invoking OnMessageReceived callback.");
                    }
                }
            }

            // free the receive buffer.
            if (_receiveBuffer != null)
            {
                _bufferManager.ReturnBuffer(_receiveBuffer, nameof(ProcessReceivedBuffer));
                _receiveBuffer = null;
            }
            // start receiving next message.
            ReceiveMessage();
            return(ServiceResult.Good);
        }
コード例 #35
0
 public static JsonModel Create(ServiceResult serviceResult)
 {
     return(new JsonModel {
         Success = serviceResult.Success
     });
 }
コード例 #36
0
ファイル: MainForm.cs プロジェクト: mcooper87/UA-.NET
        /// <summary>
        /// Changes the monitoring mode for the currently selected monitored items.
        /// </summary>
        private void Monitoring_MonitoringMode_Click(object sender, EventArgs e)
        {
            try
            {
                // check if operation is currently allowed.
                if (m_session == null || m_subscription == null || MonitoredItemsLV.SelectedItems.Count == 0)
                {
                    return;
                }

                // determine the monitoring mode being requested.
                MonitoringMode monitoringMode = MonitoringMode.Disabled;

                if (sender == Monitoring_MonitoringMode_ReportingMI)
                {
                    monitoringMode = MonitoringMode.Reporting;
                }

                if (sender == Monitoring_MonitoringMode_SamplingMI)
                {
                    monitoringMode = MonitoringMode.Sampling;
                }

                // update the monitoring mode.
                List <MonitoredItem> itemsToChange = new List <MonitoredItem>();

                for (int ii = 0; ii < MonitoredItemsLV.SelectedItems.Count; ii++)
                {
                    MonitoredItem monitoredItem = MonitoredItemsLV.SelectedItems[ii].Tag as MonitoredItem;

                    if (monitoredItem != null)
                    {
                        itemsToChange.Add(monitoredItem);
                    }
                }

                // apply the changes to the server.
                m_subscription.SetMonitoringMode(monitoringMode, itemsToChange);

                // update the display.
                for (int ii = 0; ii < itemsToChange.Count; ii++)
                {
                    ListViewItem item = itemsToChange[ii].Handle as ListViewItem;

                    if (item != null)
                    {
                        item.SubItems[8].Text = String.Empty;

                        if (ServiceResult.IsBad(itemsToChange[ii].Status.Error))
                        {
                            item.SubItems[8].Text = itemsToChange[ii].Status.Error.StatusCode.ToString();
                        }

                        item.SubItems[2].Text = itemsToChange[ii].Status.MonitoringMode.ToString();
                    }
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
コード例 #37
0
 /// <summary>
 /// Sets the error status for the monitored item.
 /// </summary>
 public void SetError(ServiceResult error)
 {
     m_status.SetError(error);
 }
コード例 #38
0
        private bool ValidateJwtAuthentication(ServiceRoute route, Dictionary <string, object> model, ref ServiceResult <object> result)
        {
            bool isSuccess = true;
            var  author    = HttpContext.Request.Headers["Authorization"];

            if (author.Count > 0)
            {
                if (route.Address.Any(p => p.DisableAuth == false))
                {
                    isSuccess = _authorizationServerProvider.ValidateClientAuthentication(author).Result;
                    if (!isSuccess)
                    {
                        result = new ServiceResult <object> {
                            IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                        };
                    }
                    else
                    {
                        var keyValue = model.FirstOrDefault();
                        if (!(keyValue.Value is IConvertible) || !typeof(IConvertible).GetTypeInfo().IsAssignableFrom(keyValue.Value.GetType()))
                        {
                            dynamic instance = keyValue.Value;
                            instance.Payload = _authorizationServerProvider.GetPayloadString(author);
                            model.Remove(keyValue.Key);
                            model.Add(keyValue.Key, instance);
                        }
                    }
                }
            }
            else
            {
                result = new ServiceResult <object> {
                    IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error"
                };
                isSuccess = false;
            }
            return(isSuccess);
        }
コード例 #39
0
 public static JsonModel Create <TDto>(ServiceResult <TDto> serviceResult)
 {
     return(new JsonModel {
         Success = serviceResult.Success, Data = serviceResult.Data
     });
 }
コード例 #40
0
ファイル: UserRightsService.cs プロジェクト: adteven/alabo
        public async Task <Tuple <ServiceResult, OrderBuyOutput> > OpenSelfOrUpgrade(UserRightsOrderInput orderInput)
        {
            var result         = ServiceResult.Success;
            var orderBuyOutput = new OrderBuyOutput();
            //if (orderInput.GradeId == Guid.Parse("72be65e6-3000-414d-972e-1a3d4a366001"))
            //{
            //    result = ServiceResult.Failure("标准商家不能自己支付开通");
            //    new Tuple<ServiceResult, OrderBuyOutput>(result, orderBuyOutput);
            //}

            var payPrice = GetPayPrice(orderInput);

            if (!payPrice.Item1.Succeeded)
            {
                return(Tuple.Create(payPrice.Item1, orderBuyOutput));
            }

            var context = Repository <IUserRightsRepository>().RepositoryContext;

            try {
                context.BeginTransaction();

                var order = new Order {
                    UserId        = orderInput.BuyUser.Id,
                    StoreId       = string.Empty,
                    OrderStatus   = OrderStatus.WaitingBuyerPay,
                    OrderType     = OrderType.VirtualOrder,
                    TotalAmount   = payPrice.Item2,
                    TotalCount    = 1,
                    PayId         = 0,
                    PaymentAmount = payPrice.Item2
                };
                // 订单扩展数据
                var userRightOrder = AutoMapping.SetValue <UserRightsOrderInput>(orderInput);

                order.OrderExtension = new OrderExtension {
                    // 价格信息
                    OrderAmount = new OrderAmount {
                        TotalProductAmount = payPrice.Item2, // 商品总价
                        ExpressAmount      = 0m,             // 邮费
                        FeeAmount          = 0m              // 服务费
                    },
                    AttachContent = userRightOrder.ToJsons(),
                    User          = orderInput.BuyUser, // 下单用户
                    Store         = null
                };

                order.AccountPay = order.AccountPayPair.ToJsons();
                order.Extension  = order.OrderExtension.ToJsons();

                // 如果发货人不为空

                Resolve <IOrderService>().Add(order);
                var orderList = new List <Order>
                {
                    order
                };
                var singlePayInput = new SinglePayInput {
                    Orders          = orderList,
                    User            = orderInput.User,
                    OrderUser       = orderInput.BuyUser,
                    ExcecuteSqlList = new BaseServiceMethod {
                        Method      = "ExcecuteSqlList",
                        ServiceName = typeof(IUserRightsService).Name,
                        Parameter   = order.Id
                    },
                    AfterSuccess = new BaseServiceMethod {
                        Method      = "AfterPaySuccess",
                        ServiceName = typeof(IUserRightsService).Name,
                        Parameter   = order.Id
                    },
                    TriggerType = TriggerType.Other,
                    BuyerCount  = 1,
                    RedirectUrl = "/pages/index?path=successful_opening"
                };
                var payResult = Resolve <IOrderAdminService>().AddSinglePay(singlePayInput);
                if (!payResult.Item1.Succeeded)
                {
                    // 支付记录添加失败,回滚
                    context.RollbackTransaction();
                    return(Tuple.Create(payResult.Item1, new OrderBuyOutput()));
                }

                //更新人民币支付记录Id
                var orderIds = orderList.Select(e => e.Id).ToList();
                Resolve <IOrderService>().Update(r => { r.PayId = payResult.Item2.Id; }, e => orderIds.Contains(e.Id));

                // 输出赋值
                orderBuyOutput.PayAmount = payResult.Item2.Amount;
                orderBuyOutput.PayId     = payResult.Item2.Id;
                orderBuyOutput.OrderIds  = orderList.Select(r => r.Id).ToList();

                //开通成功修改UserDetail表地址
                var buyUserDetail = Resolve <IUserDetailService>().GetSingle(u => u.UserId == orderInput.BuyUser.Id);
                if (buyUserDetail.RegionId <= 0)
                {
                    buyUserDetail.RegionId = orderInput.RegionId.ToInt64();
                    Resolve <IUserDetailService>().Update(buyUserDetail);
                }

                context.SaveChanges();
                context.CommitTransaction();
                //var buyUser = Resolve<IUserService>().GetSingle(u => u.Mobile == orderInput.BuyUser.Mobile);

                orderBuyOutput.RegUser  = orderInput.RegInfo;
                orderBuyOutput.BuyGrade =
                    orderInput
                    .BuyGrade;     // Resolve<IAutoConfigService>().GetList<UserGradeConfig>().FirstOrDefault(s => s.Id == orderInput.BuyUser.GradeId);
            } catch (Exception ex) {
                context.RollbackTransaction();
                result = ServiceResult.Failure(ex.Message);
            } finally {
                context.DisposeTransaction();
            }

            // 删除缓存
            Resolve <IUserService>().DeleteUserCache(orderInput.User.Id, orderInput.User.UserName);
            Resolve <IUserService>().DeleteUserCache(orderInput.BuyUser.Id, orderInput.BuyUser.UserName);
            return(new Tuple <ServiceResult, OrderBuyOutput>(result, orderBuyOutput));
        }
コード例 #41
0
ファイル: UserRightsService.cs プロジェクト: adteven/alabo
        /// <summary>
        ///     帮别人开通
        /// </summary>
        /// <param name="orderBuyInput"></param>
        /// <returns></returns>
        public async Task <Tuple <ServiceResult, OrderBuyOutput> > OpenToOther(UserRightsOrderInput orderBuyInput)
        {
            var result         = ServiceResult.Success;
            var orderBuyOutput = new OrderBuyOutput();

            // 检查用户的名额
            var userGrades = Resolve <IAutoConfigService>().GetList <UserGradeConfig>();
            var userRight  = GetSingle(r => r.UserId == orderBuyInput.User.Id && r.GradeId == orderBuyInput.GradeId);

            if (userRight == null)
            {
                return(Tuple.Create(ServiceResult.Failure($"您无{orderBuyInput.BuyGrade?.Name}名额端口"),
                                    orderBuyOutput));
            }

            if (userRight.TotalCount - userRight.TotalUseCount < 1)
            {
                return(Tuple.Create(ServiceResult.Failure($"您{orderBuyInput.BuyGrade?.Name}名额端口,已用完"),
                                    orderBuyOutput));
            }

            if (orderBuyInput.BuyUser == null)
            {
                return(Tuple.Create(ServiceResult.Failure("新会员未注册成功"), orderBuyOutput));
            }

            var context = Repository <IUserRightsRepository>().RepositoryContext;

            try {
                context.BeginTransaction();
                var kpi = new Kpi {
                    ModuleId = orderBuyInput.GradeId,
                    UserId   = orderBuyInput.UserId,
                    Type     = TimeType.NoLimit,
                    Value    = 1
                };
                var lastKpiSingle = Resolve <IKpiService>()
                                    .GetSingle(r => r.ModuleId == orderBuyInput.GradeId && r.Type == TimeType.NoLimit);
                if (lastKpiSingle != null)
                {
                    kpi.TotalValue = lastKpiSingle.TotalValue + kpi.Value;
                }

                // 新增Kpi记录,使用Kpi 记录表保存记录数据
                Resolve <IKpiService>().Add(kpi);

                // 使用数+1
                userRight.TotalUseCount += 1;
                Update(userRight);

                // 修改等级
                var updateUser = Resolve <IUserService>().GetSingle(r => r.Id == orderBuyInput.BuyUser.Id);
                updateUser.GradeId = orderBuyInput.GradeId;
                Resolve <IUserService>().Update(updateUser);

                // 增加相关权益
                // 添加用户权益
                var userRightConfigList = Resolve <IAutoConfigService>().GetList <UserRightsConfig>();
                var userRightConfig     = userRightConfigList.FirstOrDefault(r => r.GradeId == orderBuyInput.GradeId);
                if (userRightConfig != null)
                {
                    var addList = new List <UserRights>();
                    foreach (var rightItem in userRightConfig.UserRightItems)
                    {
                        var addItem = new UserRights {
                            GradeId    = rightItem.GradeId,
                            TotalCount = rightItem.Count,
                            UserId     = orderBuyInput.BuyUser.Id
                        };
                        addList.Add(addItem);
                    }

                    if (addList.Count > 0)
                    {
                        AddMany(addList);
                    }
                }

                //开通成功修改UserDetail表地址
                var buyUserDetail = Resolve <IUserDetailService>().GetSingle(u => u.UserId == orderBuyInput.BuyUser.Id);
                if (buyUserDetail.RegionId <= 0)
                {
                    buyUserDetail.RegionId = orderBuyInput.RegionId.ToInt64();
                    Resolve <IUserDetailService>().Update(buyUserDetail);
                }

                context.SaveChanges();
                context.CommitTransaction();
                //orderBuyOutput.RegUser = orderBuyInput.RegInfo;
                //orderBuyOutput.BuyGrade = orderBuyInput.BuyGrade;
                //var buyUser = Resolve<IUserService>().GetSingle(u => u.Mobile == orderBuyInput.BuyUser.Mobile);

                orderBuyOutput.RegUser  = orderBuyInput.RegInfo;
                orderBuyOutput.BuyGrade =
                    orderBuyInput
                    .BuyGrade;     // Resolve<IAutoConfigService>().GetList<UserGradeConfig>().FirstOrDefault(s => s.Id == orderBuyInput.BuyUser.GradeId);
            } catch (Exception ex) {
                context.RollbackTransaction();
                result = ServiceResult.Failure(ex.Message);
            } finally {
                context.DisposeTransaction();
            }

            SendMessage(orderBuyInput.BuyUser, orderBuyInput.GradeId);
            return(Tuple.Create(result, orderBuyOutput));
        }
コード例 #42
0
        private bool ValidateAppSecretAuthentication(ServiceRoute route, string path,
                                                     Dictionary <string, object> model, ref ServiceResult <object> result)
        {
            bool     isSuccess = true;
            DateTime time;
            var      author = HttpContext.Request.Headers["Authorization"];

            if (route.Address.Any(p => p.DisableAuth == false))
            {
                if (!string.IsNullOrEmpty(path) && model.ContainsKey("timeStamp") && author.Count > 0)
                {
                    if (DateTime.TryParse(model["timeStamp"].ToString(), out time))
                    {
                        var seconds = (DateTime.Now - time).TotalSeconds;
                        if (seconds <= 3560 && seconds >= 0)
                        {
                            if (!route.Address.Any(p => GetMD5($"{p.Token}{time.ToString("yyyy-MM-dd hh:mm:ss") }") == author.ToString()))
                            {
                                result = new ServiceResult <object> {
                                    IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                                };
                                isSuccess = false;
                            }
                        }
                        else
                        {
                            result = new ServiceResult <object> {
                                IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                            };
                            isSuccess = false;
                        }
                    }
                    else
                    {
                        result = new ServiceResult <object> {
                            IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                        };
                        isSuccess = false;
                    }
                }
                else
                {
                    result = new ServiceResult <object> {
                        IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error"
                    };
                    isSuccess = false;
                }
            }
            return(isSuccess);
        }
コード例 #43
0
        public async Task <ServiceResult <object> > DomainPermissions(CommonCMDReq req)
        {
            var result = await _authProxy.FindDomainPermissions(req);

            return(ServiceResult <object> .Create(true, result));
        }
コード例 #44
0
        public async Task <ServiceResult <object> > SignIn(LoginReq req)
        {
            //要注意参数类型
            var model = new Dictionary <string, object>();

            model.Add("req", JsonConvert.SerializeObject(req));
            var serviceKey = "Auth";
            ServiceResult <object> result = ServiceResult <object> .Create(false, null);

            var path = GateWayAppConfig.AuthorizationRoutePath;

            if (OnAuthorization(path, model, ref result))
            {
                if (path == GateWayAppConfig.AuthorizationRoutePath)
                {
                    var token = await _authorizationServerProvider.GenerateTokenCredential(model);

                    if (token != null)
                    {
                        //查询当前用户的权限,返回给客户端
                        var tmp      = JsonConvert.DeserializeObject <string>(_authorizationServerProvider.GetPayloadString(token));
                        var identify = JsonConvert.DeserializeObject <TokenDto>(tmp);
                        Dictionary <string, object> reqQueryUserPermission = new Dictionary <string, object>();
                        reqQueryUserPermission.Add("req", JsonConvert.SerializeObject(new
                        {
                            Identify = identify
                        }));
                        string servicePath = "api/orgapp/QueryUserPermission";
                        var    res         = await _serviceProxyProvider.Invoke <BaseListResponseDto>(reqQueryUserPermission, servicePath);

                        if (res != null && res.OperateFlag)
                        {
                            result = ServiceResult <object> .Create(true, new { token = token, auth = res.Result });

                            result.StatusCode = (int)ServiceStatusCode.Success;
                        }
                        else
                        {
                            result = new ServiceResult <object> {
                                IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                            };
                        }
                    }
                    else
                    {
                        result = new ServiceResult <object> {
                            IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                        };
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(serviceKey))
                    {
                        result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path, serviceKey));

                        result.StatusCode = (int)ServiceStatusCode.Success;
                    }
                    else
                    {
                        result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path));

                        result.StatusCode = (int)ServiceStatusCode.Success;
                    }
                }
            }
            return(result);
        }
コード例 #45
0
ファイル: MainForm.cs プロジェクト: mcooper87/UA-.NET
        /// <summary>
        /// Changes the deadband for the currently selected monitored items.
        /// </summary>
        private void Monitoring_Deadband_Click(object sender, EventArgs e)
        {
            try
            {
                // check if operation is currently allowed.
                if (m_session == null || m_subscription == null || MonitoredItemsLV.SelectedItems.Count == 0)
                {
                    return;
                }

                // determine the filter being requested.
                DataChangeFilter filter = new DataChangeFilter();
                filter.Trigger = DataChangeTrigger.StatusValue;

                if (sender == Monitoring_Deadband_Absolute_5MI)
                {
                    filter.DeadbandType  = (uint)DeadbandType.Absolute;
                    filter.DeadbandValue = 5.0;
                }
                else if (sender == Monitoring_Deadband_Absolute_10MI)
                {
                    filter.DeadbandType  = (uint)DeadbandType.Absolute;
                    filter.DeadbandValue = 10.0;
                }
                else if (sender == Monitoring_Deadband_Absolute_25MI)
                {
                    filter.DeadbandType  = (uint)DeadbandType.Absolute;
                    filter.DeadbandValue = 25.0;
                }
                else if (sender == Monitoring_Deadband_Percentage_1MI)
                {
                    filter.DeadbandType  = (uint)DeadbandType.Percent;
                    filter.DeadbandValue = 1.0;
                }
                else if (sender == Monitoring_Deadband_Percentage_5MI)
                {
                    filter.DeadbandType  = (uint)DeadbandType.Percent;
                    filter.DeadbandValue = 5.0;
                }
                else if (sender == Monitoring_Deadband_Percentage_10MI)
                {
                    filter.DeadbandType  = (uint)DeadbandType.Percent;
                    filter.DeadbandValue = 10.0;
                }
                else
                {
                    filter = null;
                }

                // update the monitoring mode.
                List <MonitoredItem> itemsToChange = new List <MonitoredItem>();

                for (int ii = 0; ii < MonitoredItemsLV.SelectedItems.Count; ii++)
                {
                    MonitoredItem monitoredItem = MonitoredItemsLV.SelectedItems[ii].Tag as MonitoredItem;

                    if (monitoredItem != null)
                    {
                        monitoredItem.Filter = filter;
                        itemsToChange.Add(monitoredItem);
                    }
                }

                // apply the changes to the server.
                m_subscription.ApplyChanges();

                // update the display.
                for (int ii = 0; ii < itemsToChange.Count; ii++)
                {
                    ListViewItem item = itemsToChange[ii].Handle as ListViewItem;

                    if (item != null)
                    {
                        item.SubItems[8].Text = String.Empty;

                        if (ServiceResult.IsBad(itemsToChange[ii].Status.Error))
                        {
                            itemsToChange[ii].Filter = null;
                            item.SubItems[8].Text    = itemsToChange[ii].Status.Error.StatusCode.ToString();
                        }

                        item.SubItems[4].Text = DeadbandFilterToText(itemsToChange[ii].Status.Filter);
                    }
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
コード例 #46
0
        public async Task <ServiceResult <Dictionary <string, Guid> > > Update(ExcelCellValueLookup entries, Guid userId, Guid costId, Guid costStageRevisionId)
        {
            if (entries == null)
            {
                Logger.Warning("Param entries is null reference. This means the uploaded budget form was not read correctly.");
                return(ServiceResult <Dictionary <string, Guid> > .CreateFailedResult(TechnicalErrorMessage));
            }
            if (userId == Guid.Empty)
            {
                Logger.Warning("Param userId is Guid.Empty.");
                return(ServiceResult <Dictionary <string, Guid> > .CreateFailedResult(TechnicalErrorMessage));
            }
            if (costId == Guid.Empty)
            {
                Logger.Warning("Param costId is Guid.Empty.");
                return(ServiceResult <Dictionary <string, Guid> > .CreateFailedResult(TechnicalErrorMessage));
            }
            if (costStageRevisionId == Guid.Empty)
            {
                Logger.Warning("Param costStageRevisionId is Guid.Empty.");
                return(ServiceResult <Dictionary <string, Guid> > .CreateFailedResult(TechnicalErrorMessage));
            }
            if (entries.Count == 0)
            {
                Logger.Warning("Param entries is empty collection. This means the uploaded budget form was not read correctly.");
                return(ServiceResult <Dictionary <string, Guid> > .CreateFailedResult(TechnicalErrorMessage));
            }

            var stageForm = await _costStageRevisionService.GetStageDetails <PgStageDetailsForm>(costStageRevisionId);

            var productionForm = await _costStageRevisionService.GetProductionDetails <PgProductionDetailsForm>(costStageRevisionId);

            var costStageRevision = await _efContext.CostStageRevision
                                    .Include(csr => csr.CostStage)
                                    .ThenInclude(csr => csr.CostStageRevisions)
                                    .FirstOrDefaultAsync(c => c.Id == costStageRevisionId);

            //Update the Agency Currency, if different
            var agencyCurrencyCode = GetAgencyCurrencyCode(entries);

            // return a dictionary of the currencies that have been modified i.e. agency, dpv, section.
            // Key is agency, dpv or section name and value is the currencyId. The FE has all the Ids and can update itself.
            var currencies    = new Dictionary <string, Guid>();
            var serviceResult = new ServiceResult <Dictionary <string, Guid> >(currencies);

            if (stageForm.AgencyCurrency != agencyCurrencyCode)
            {
                if (CanUpdateAgencyCurrency(costStageRevision))
                {
                    var stageDetails = await _efContext.CustomFormData.FirstOrDefaultAsync(c => c.Id == costStageRevision.StageDetailsId);

                    UpdateAgencyCurrency(stageDetails, agencyCurrencyCode);
                    var agencyCurrencyId = await GetCurrencyId(agencyCurrencyCode);

                    currencies[AgencyCurrencyKey] = agencyCurrencyId;
                }
                else
                {
                    var error = new FeedbackMessage(
                        $"The agency currency you have chosen in the budget form, {agencyCurrencyCode} does not match your datasheet of {stageForm.AgencyCurrency}. There are two options to progress this:");
                    error.AddSuggestion("You may change the currency of your budget form to match the datasheet currency and re-upload the Budget form.");
                    error.AddSuggestion(
                        "You may cancel this datasheet, create a new cost and select the required agency currency. After cancelling your cost please contact P&G. They will raise and issue credit for any monies you have received against the original PO.");
                    serviceResult.AddError(error);

                    return(serviceResult);
                }
            }

            // The Cost Section Currencies done by the ICostLineItemUpdater because each CostLineItem has a currency.
            // On the UI, the Cost Section currency is set by rolling up from the first CostLineItem.

            // Here we extrapolate the currencies for the DPV and the cost line item sections in order to simplify the
            // front end code. At this present time, the FE calculates the CLI Section currency based on the first item it finds.
            if (productionForm.DirectPaymentVendor != null)
            {
                var dpvCurrencyCode = GetDpvCurrencyCode(entries, stageForm);
                var dpvCurrencyId   = await GetCurrencyId(dpvCurrencyCode);

                var productionDetails = await _efContext.CustomFormData.FirstOrDefaultAsync(c => c.Id == costStageRevision.ProductDetailsId);

                UpdateDpvCurrency(productionDetails, dpvCurrencyId);
                currencies[DirectPaymentVendorCurrencyKey] = dpvCurrencyId;
            }

            return(serviceResult);
        }
コード例 #47
0
ファイル: MainForm.cs プロジェクト: mcooper87/UA-.NET
        /// <summary>
        /// Changes the sampling interval for the currently selected monitored items.
        /// </summary>
        private void Monitoring_SamplingInterval_Click(object sender, EventArgs e)
        {
            try
            {
                // check if operation is currently allowed.
                if (m_session == null || m_subscription == null || MonitoredItemsLV.SelectedItems.Count == 0)
                {
                    return;
                }

                // determine the sampling interval being requested.
                double samplingInterval = 0;

                if (sender == Monitoring_SamplingInterval_1000MI)
                {
                    samplingInterval = 1000;
                }
                else if (sender == Monitoring_SamplingInterval_2500MI)
                {
                    samplingInterval = 2500;
                }
                else if (sender == Monitoring_SamplingInterval_5000MI)
                {
                    samplingInterval = 5000;
                }

                // update the monitoring mode.
                List <MonitoredItem> itemsToChange = new List <MonitoredItem>();

                for (int ii = 0; ii < MonitoredItemsLV.SelectedItems.Count; ii++)
                {
                    MonitoredItem monitoredItem = MonitoredItemsLV.SelectedItems[ii].Tag as MonitoredItem;

                    if (monitoredItem != null)
                    {
                        monitoredItem.SamplingInterval = (int)samplingInterval;
                        itemsToChange.Add(monitoredItem);
                    }
                }

                // apply the changes to the server.
                m_subscription.ApplyChanges();

                // update the display.
                for (int ii = 0; ii < itemsToChange.Count; ii++)
                {
                    ListViewItem item = itemsToChange[ii].Handle as ListViewItem;

                    if (item != null)
                    {
                        item.SubItems[8].Text = String.Empty;

                        if (ServiceResult.IsBad(itemsToChange[ii].Status.Error))
                        {
                            item.SubItems[8].Text = itemsToChange[ii].Status.Error.StatusCode.ToString();
                        }

                        item.SubItems[3].Text = itemsToChange[ii].Status.SamplingInterval.ToString();
                    }
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
コード例 #48
0
        /// <summary>
        /// Action加上[SupportFilter]在执行actin之前执行以下代码,通过[SupportFilter(ActionName="Index")]指定参数
        /// </summary>
        /// <param name="filterContext">页面传过来的上下文</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //读取请求上下文中的Controller,Action,Id
            var routes = new RouteCollection();

            RouteConfig.RegisterRoutes(routes);
            RouteData routeData = routes.GetRouteData(filterContext.HttpContext);
            //取出区域的控制器Action,id
            string ctlName = filterContext.Controller.ToString();

            string[] routeInfo  = ctlName.Split('.');
            string   controller = null;
            string   action     = null;
            string   id         = null;

            int iAreas = Array.IndexOf(routeInfo, "Areas");

            if (iAreas > 0)
            {
                //取区域及控制器
                Area = routeInfo[iAreas + 1];
            }
            //int ctlIndex = Array.IndexOf(routeInfo, "Controllers");
            //ctlIndex++;
            int ctlIndex = routeInfo.Length - 1;

            controller = routeInfo[ctlIndex].Replace("Controller", "").ToLower();

            string url = HttpContext.Current.Request.Url.ToString().ToLower();

            string[] urlArray    = url.Split('/');
            int      urlCtlIndex = Array.IndexOf(urlArray, controller);

            urlCtlIndex++;
            if (urlArray.Count() > urlCtlIndex)
            {
                action = urlArray[urlCtlIndex];
            }
            urlCtlIndex++;
            if (urlArray.Count() > urlCtlIndex)
            {
                id = urlArray[urlCtlIndex];
            }
            //url
            action = ValidateHelper.IsNullOrEmpty(action) ? "Index" : action;
            int actionIndex = action.IndexOf("?", 0);

            if (actionIndex > 1)
            {
                action = action.Substring(0, actionIndex);
            }
            id = ValidateHelper.IsNullOrEmpty(id) ? "" : id;

            //URL路径
            string actionPath = HttpContext.Current.Request.FilePath;

            if (filterContext.HttpContext.Request.UrlReferrer == null)
            {
                filterContext.Result = new EmptyResult();
                string js = "<script language='javascript'>alert('{0}');</script>";
                filterContext.HttpContext.Response.Write(string.Format(js, "你没有操作权限,请联系管理员"));
                filterContext.HttpContext.Response.End();
                return;
            }
            string       filePath = filterContext.HttpContext.Request.UrlReferrer.AbsolutePath;
            AccountModel account  = filterContext.HttpContext.Session["Account"] as AccountModel;

            if (ValiddatePermission(account, controller, action, actionPath, filePath))
            {
                return;
            }
            else
            {
                filterContext.Result = new EmptyResult();
                filterContext.HttpContext.Response.ContentType = "application/json";
                JsonMessage jsonMsg = ServiceResult.Message(0, "你没有操作权限,请联系管理员");
                filterContext.HttpContext.Response.Write("{\"type\":0,\"message\":\"你没有操作权限,请联系管理员\"}");
                filterContext.HttpContext.Response.End();
                return;
            }
        }
コード例 #49
0
ファイル: MainForm.cs プロジェクト: mcooper87/UA-.NET
        /// <summary>
        /// Handles the Click event of the Monitoring_DeleteMI control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Monitoring_DeleteMI_Click(object sender, EventArgs e)
        {
            try
            {
                // check if operation is currently allowed.
                if (MonitoredItemsLV.SelectedItems.Count == 0)
                {
                    return;
                }

                // collect the items to delete.
                List <ListViewItem> itemsToDelete = new List <ListViewItem>();

                for (int ii = 0; ii < MonitoredItemsLV.SelectedItems.Count; ii++)
                {
                    MonitoredItem monitoredItem = MonitoredItemsLV.SelectedItems[ii].Tag as MonitoredItem;

                    if (monitoredItem != null)
                    {
                        monitoredItem.Notification -= m_MonitoredItem_Notification;
                        itemsToDelete.Add(MonitoredItemsLV.SelectedItems[ii]);

                        if (m_subscription != null)
                        {
                            m_subscription.RemoveItem(monitoredItem);
                        }
                    }
                }

                // update the server.
                if (m_subscription != null)
                {
                    m_subscription.ApplyChanges();

                    // check the status.
                    for (int ii = 0; ii < itemsToDelete.Count; ii++)
                    {
                        MonitoredItem monitoredItem = itemsToDelete[ii].Tag as MonitoredItem;

                        if (ServiceResult.IsBad(monitoredItem.Status.Error))
                        {
                            itemsToDelete[ii].SubItems[8].Text = monitoredItem.Status.Error.StatusCode.ToString();
                            continue;
                        }
                    }
                }

                // remove the items.
                for (int ii = 0; ii < itemsToDelete.Count; ii++)
                {
                    itemsToDelete[ii].Remove();
                }

                MonitoredItemsLV.Columns[0].Width = -2;
                MonitoredItemsLV.Columns[1].Width = -2;
                MonitoredItemsLV.Columns[8].Width = -2;
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
コード例 #50
0
        public ServiceResult CreateMultiPagePDFFile(List <Dictionary <string, string> > pdfDataLst, string pdfTemplate, bool lockForm)
        {
            if (log.IsDebugEnabled)
            {
                log.Debug("Start");
            }

            ServiceResult wsResult = new ServiceResult();

            try
            {
                if (pdfDataLst == null || pdfDataLst.Count == 0)
                {
                    wsResult.KodOdpovede = 1;
                    wsResult.StatusText  = "Nevyplnený vstupný parameter pdfData";

                    if (log.IsDebugEnabled)
                    {
                        log.Debug(wsResult.StatusText);
                    }

                    return(wsResult);
                }

                if (string.IsNullOrWhiteSpace(pdfTemplate))
                {
                    wsResult.KodOdpovede = 1;
                    wsResult.StatusText  = "Nevyplnený vstupný parameter pdfTemplate";

                    if (log.IsDebugEnabled)
                    {
                        log.Debug(wsResult.StatusText);
                    }

                    return(wsResult);
                }

                pdfTemplate = HostingEnvironment.MapPath(pdfTemplate);

                using (Document document = new Document())
                {
                    using (MemoryStream msDoc = new MemoryStream())
                    {
                        PdfCopy copy = new PdfSmartCopy(document, msDoc);
                        document.Open();

                        foreach (Dictionary <string, string> pdfData in pdfDataLst)
                        {
                            using (PdfReader pdfReaderDoc = new PdfReader(CreatePdf(pdfData, pdfTemplate, lockForm)))
                            {
                                copy.AddDocument(pdfReaderDoc);
                                pdfReaderDoc.Close();
                            }
                        }

                        document.Close();
                        wsResult.FileData = msDoc.ToArray();
                    }
                }

                if (log.IsDebugEnabled)
                {
                    log.Debug("Stop");
                }

                return(wsResult);
            }
            catch (Exception ex)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Interna chyba: ", ex);
                }

                wsResult.KodOdpovede = -1;
                wsResult.StatusText  = string.Concat("Chyba pri spracovaní dokumentu: ", ex.Message);
                return(wsResult);
            }
        }
コード例 #51
0
        /// <summary>
        /// Updates the status control when a keep alive event occurs.
        /// </summary>
        void StandardClient_KeepAlive(Session sender, KeepAliveEventArgs e)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new KeepAliveEventHandler(StandardClient_KeepAlive), sender, e);
                return;
            }
            else if (!IsHandleCreated)
            {
                return;
            }

            if (sender != null && sender.Endpoint != null)
            {
                ServerUrlLB.Text = Utils.Format(
                    "{0} ({1}) {2}",
                    sender.Endpoint.EndpointUrl,
                    sender.Endpoint.SecurityMode,
                    (sender.EndpointConfiguration.UseBinaryEncoding)?"UABinary":"XML");
            }
            else
            {
                ServerUrlLB.Text = "None";
            }

            if (e != null && m_session != null)
            {
                if (ServiceResult.IsGood(e.Status))
                {
                    ServerStatusLB.Text = Utils.Format(
                        "Server Status: {0} {1:yyyy-MM-dd HH:mm:ss} {2}/{3}",
                        e.CurrentState,
                        e.CurrentTime.ToLocalTime(),
                        m_session.OutstandingRequestCount,
                        m_session.DefunctRequestCount);

                    ServerStatusLB.ForeColor = Color.Empty;
                    ServerStatusLB.Font      = new Font(ServerStatusLB.Font, FontStyle.Regular);
                }
                else
                {
                    ServerStatusLB.Text = String.Format(
                        "{0} {1}/{2}", e.Status,
                        m_session.OutstandingRequestCount,
                        m_session.DefunctRequestCount);

                    ServerStatusLB.ForeColor = Color.Red;
                    ServerStatusLB.Font      = new Font(ServerStatusLB.Font, FontStyle.Bold);

                    if (m_reconnectPeriod <= 0)
                    {
                        return;
                    }

                    if (m_reconnectHandler == null && m_reconnectPeriod > 0)
                    {
                        m_reconnectHandler = new SessionReconnectHandler();
                        m_reconnectHandler.BeginReconnect(m_session, m_reconnectPeriod * 1000, StandardClient_Server_ReconnectComplete);
                    }
                }
            }
        }
コード例 #52
0
 public Result(ServiceResult serviceResult, T data)
 {
     ServiceResult = serviceResult;
     Data          = data;
 }
コード例 #53
0
ファイル: LogController.cs プロジェクト: Twtcer/mbill_service
 public async Task <ServiceResult <PagedDto <LogDto> > > GetPagesAsync([FromQuery] LogPagingDto pagingDto)
 {
     return(ServiceResult <PagedDto <LogDto> > .Successed(await _logService.GetPagesAsync(pagingDto)));
 }
コード例 #54
0
 public Result(ServiceResult serviceResult) : this(serviceResult, default(T))
 {
 }
コード例 #55
0
ファイル: UserRightsService.cs プロジェクト: adteven/alabo
        /// <summary>
        ///     获取需要支付的价格
        /// </summary>
        public Tuple <ServiceResult, decimal> GetPayPrice(UserRightsOrderInput orderInput)
        {
            var result = ServiceResult.Success;

            if (orderInput.OpenType == UserRightOpenType.OpenToOtherByRight)
            {
                return(Tuple.Create(ServiceResult.Failure("帮他购买时无价格计算"), 0m));
            }

            if (orderInput.OpenType == UserRightOpenType.OpenToOtherByPay)
            {
                if (orderInput.User.Id == orderInput.BuyUser.Id)
                {
                    return(Tuple.Create(ServiceResult.Failure("不能帮自己购买"), 0m));
                }

                var price = orderInput.BuyGrade.Price;
                return(Tuple.Create(result, price));
            }
            else
            {
                if (orderInput.BuyGrade.Price <= orderInput.CurrentGrade.Price &&
                    orderInput.OpenType != UserRightOpenType.AdminOpenHightGrade)
                {
                    return(Tuple.Create(ServiceResult.Failure("购买的等级不能低于当前等级"), 0m));
                }

                var findRight = orderInput.UserRightList.FirstOrDefault(r => r.GradeId == orderInput.BuyGrade.Id);
                if (findRight != null && orderInput.OpenType != UserRightOpenType.AdminOpenHightGrade)
                {
                    return(Tuple.Create(ServiceResult.Failure("用户当前等级权益已存在,不能重复购买"), 0m));
                }

                var userRightsConfigs = Resolve <IAutoConfigService>().GetList <UserRightsConfig>();
                var userGrades        = Resolve <IAutoConfigService>().GetList <UserGradeConfig>();
                // 如果包含,则为升级
                if (userRightsConfigs.Select(r => r.GradeId).Contains(orderInput.User.GradeId))
                {
                    if (orderInput.OpenType != UserRightOpenType.Upgrade &&
                        orderInput.OpenType != UserRightOpenType.AdminOpenHightGrade)
                    {
                        return(Tuple.Create(ServiceResult.Failure("开通方式有错,应该为自身升级"), 0m));
                    }
                }
                else
                {
                    if (orderInput.OpenType != UserRightOpenType.OpenSelf)
                    {
                        return(Tuple.Create(ServiceResult.Failure("开通方式有错,应该为自身购买"), 0m));
                    }
                }

                // 计算价格
                var price = orderInput.BuyGrade.Price;
                if (orderInput.OpenType == UserRightOpenType.Upgrade)
                {
                    price = orderInput.BuyGrade.Price - orderInput.CurrentGrade.Price;
                }

                if (price <= 0)
                {
                    return(Tuple.Create(ServiceResult.Failure("购买等级价格设置为0"), 0m));
                }

                if (price != orderInput.Price)
                {
                    return(Tuple.Create(ServiceResult.Failure("前后台计算价格不一样"), 0m));
                }

                return(Tuple.Create(result, price));
            }
        }
コード例 #56
0
ファイル: AggregateUnitTest.cs プロジェクト: fr830/OPCUA.NET
        void RunTest(AggregateType aggregate)
        {
            try
            {
                AggregateTestResultSet myResults = AggregateTestResultSet.LoadFromXMLFile(
                    String.Format(@"{0}TestResult.xml", Enum.GetName(typeof(AggregateType), aggregate)));

                for (int i = 0; i < myResults.Count; i++)
                {
                    AggregateTestResult testResult = myResults[i] as AggregateTestResult;

                    Debug.WriteLine(String.Format("Test Data: {0}", testResult.TestDataName));
                    Debug.WriteLine(String.Format("Start time: {0}\tEnd time: {1}\tInterval: {2}",
                                                  testResult.Details.StartTime.TimeOfDay,
                                                  testResult.Details.EndTime.TimeOfDay,
                                                  testResult.Details.ProcessingInterval));
                    // get expected values
                    List <DataValue> expected = new List <DataValue>(testResult.DataValues.Count);
                    for (int ii = 0; ii < testResult.DataValues.Count; ii++)
                    {
                        expected.Add(testResult.DataValues[ii].GetDataValue());
                    }

                    // configure the aggregate calculator
                    NewAggregateFilter filter = new NewAggregateFilter()
                    {
                        StartTime              = testResult.Details.StartTime,
                        EndTime                = testResult.Details.EndTime,
                        AggregateType          = AggregateLookup[aggregate],
                        AggregateConfiguration = TestData[myResults[i].TestDataName].Configuration.AggregateConfiguration,
                        ProcessingInterval     = testResult.Details.ProcessingInterval
                    };
                    TestData testData = TestData[testResult.TestDataName];
                    AggregateCalculatorImpl calculator = Aggregators.CreateAggregator(filter, testData.Configuration.Stepped);

                    /*
                     * calculator.Configuration = new AggregateConfiguration()
                     * {
                     *  PercentDataBad = 0,
                     *  PercentDataGood = 100,
                     *  SteppedSlopedExtrapolation = false,
                     *  TreatUncertainAsBad = true
                     * };
                     */
                    HistoryData rawHistoryData = new HistoryData();
                    for (int ii = 0; ii < testData.DataValues.Count; ii++)
                    {
                        DataValue dv = testData.DataValues[ii].GetDataValue();
                        rawHistoryData.DataValues.Add(dv);
                    }

                    HistoryData historyData = new HistoryData();
                    var         sr          = new ServiceResult(StatusCodes.Good);
                    foreach (DataValue raw in rawHistoryData.DataValues)
                    {
                        IList <DataValue> released = calculator.ProcessValue(raw, sr);
                        if (StatusCode.IsGood(sr.StatusCode) && released.Count > 0)
                        {
                            historyData.DataValues.AddRange(released);
                        }
                    }
                    var lsr = new ServiceResult(StatusCodes.Good);
                    historyData.DataValues.AddRange(calculator.ProcessTermination(lsr));

                    // obtain the actual values
                    List <DataValue> actual = new List <DataValue>(historyData.DataValues);

                    // compare the two value sets
                    bool assertion = true;
                    HelperMethods.CompareResults(expected, actual, testResult.TestDataName, assertion);
                    Console.WriteLine("Test {0} passed", i);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
                throw;
            }
        }
コード例 #57
0
        public ActionResult AddOrEdit(Moduls infos, bool isdecode = false)
        {
            ServiceResult result = new ServiceResult();

            try
            {
                if (dzaccount == null)
                {
                    return(Redirect("/dzhome/login"));
                }
                if (infos == null)
                {
                    return(Json(result.IsFailed("系统繁忙auth_limited !")));
                }

                #region Base64解密
                if (isdecode)
                {
                    string decode;
                    try
                    {
                        string strDescription = infos.Content.Replace(" ", "+");
                        byte[] bytes          = Convert.FromBase64String(strDescription);
                        decode = Encoding.UTF8.GetString(bytes);
                    }
                    catch
                    {
                        decode = infos.Content;
                    }

                    infos.Content = decode;
                    string content = StringHelper.NoHtml(infos.Content.Replace("&nbsp;", ""));
                }

                #endregion
                if (infos.Id == 0)
                {
                    infos.State      = 1;
                    infos.Createdate = DateTime.Now;
                    infos.Lastdate   = DateTime.Now;
                    object id = ModulsBLL.SingleModel.Add(infos);
                    infos.Id = int.Parse(id.ToString());
                    result.IsSucceed("添加成功 !");

                    result.Data = new Dictionary <string, object> {
                        { "datas", infos }
                    };
                }
                else
                {
                    //判断是否为动态新闻模块
                    if ((int)Miapp_Miniappmoduls_Level.EightModel == infos.Level)
                    {
                        //获取新闻动态模板背景色
                        Moduls model2 = ModulsBLL.SingleModel.GetModel("appId=" + infos.appId + " and State = 1 and Level=" + (int)Miapp_Miniappmoduls_Level.NightModel);
                        if (model2 != null)
                        {
                            //修改动态新闻背景色
                            model2.Color = infos.Color;
                            ModulsBLL.SingleModel.Update(model2, "Color");
                        }
                        else
                        {
                            //添加动态新闻背景色
                            model2            = new Moduls();
                            model2.appId      = infos.appId;
                            model2.Level      = (int)Miapp_Miniappmoduls_Level.NightModel;
                            model2.State      = 1;
                            model2.Createdate = DateTime.Now;
                            model2.Lastdate   = DateTime.Now;
                            model2.Title      = "动态新闻背景色";
                            ModulsBLL.SingleModel.Add(model2);
                        }
                    }

                    string updatecolumn = "Lastdate,Hidden,Content,ImgUrl,Content2,Name,Level,LitleImgUrl,Title,Address,AddressPoint,mobile,Color,State";
                    if (infos.State == 0)
                    {
                        updatecolumn = "Lastdate,State";
                        result.IsSucceed("删除成功 !");
                    }
                    else
                    {
                        result.IsSucceed("修改成功 !");
                    }
                    infos.Lastdate = DateTime.Now;

                    ModulsBLL.SingleModel.Update(infos, updatecolumn);
                    result.Data = new Dictionary <string, object> {
                        { "datas", infos }
                    };
                }

                //首页轮播图
                if (!string.IsNullOrEmpty(infos.ImgUrl) && infos.Level == 1)
                {
                    string[] imgArray = infos.ImgUrl.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (imgArray.Length > 0)
                    {
                        foreach (string item in imgArray.Where(item => !string.IsNullOrEmpty(item) && item.IndexOf("http://", StringComparison.Ordinal) == 0))
                        {
                            C_AttachmentBLL.SingleModel.Add(new C_Attachment
                            {
                                itemId     = infos.Id,
                                createDate = DateTime.Now,
                                filepath   = item,
                                itemType   = (int)AttachmentItemType.小程序官网首页轮播图,
                                thumbnail  = item,
                                status     = 0
                            });
                        }
                    }
                    infos.ImgUrl = "";
                }

                return(Json(result));
            }
            catch (Exception ex)
            {
                return(Json(result.IsFailed("服务器出错 , 请重试 !" + ex.Message)));
            }
        }
コード例 #58
0
        /// <see cref="BaseListCtrl.UpdateItem" />
        protected override void UpdateItem(ListViewItem listItem, object item)
        {
            MonitoredItem monitoredItem = item as MonitoredItem;

            if (monitoredItem == null)
            {
                base.UpdateItem(listItem, item);
                return;
            }

            listItem.SubItems[0].Text = String.Format("{0}", monitoredItem.Status.Id);
            listItem.SubItems[1].Text = String.Format("{0}", monitoredItem.DisplayName);
            listItem.SubItems[2].Text = String.Format("{0}", monitoredItem.NodeClass);
            listItem.SubItems[3].Text = String.Format("{0}", monitoredItem.StartNodeId);
            listItem.SubItems[4].Text = String.Format("{0}", monitoredItem.RelativePath);
            listItem.SubItems[5].Text = String.Format("{0}", Attributes.GetBrowseName(monitoredItem.AttributeId));
            listItem.SubItems[6].Text = String.Format("{0}", monitoredItem.IndexRange);
            listItem.SubItems[7].Text = String.Format("{0}", monitoredItem.Encoding);
            listItem.SubItems[8].Text = String.Format("{0}", monitoredItem.MonitoringMode);
            listItem.SubItems[9].Text = String.Format("{0}", monitoredItem.SamplingInterval);

            double revisedSampingInterval = monitoredItem.Created ? monitoredItem.Status.SamplingInterval : (double)0.0;

            listItem.SubItems[10].Text = String.Format("{0}", revisedSampingInterval);
            listItem.SubItems[11].Text = String.Format("{0}", monitoredItem.QueueSize);

            uint revisedQueueSize = monitoredItem.Created ? monitoredItem.Status.QueueSize : 0;

            listItem.SubItems[12].Text = String.Format("{0}", revisedQueueSize);
            listItem.SubItems[13].Text = String.Format("{0}", monitoredItem.DiscardOldest);
            listItem.SubItems[14].Text = String.Format("{0}", monitoredItem.Status.Error);

            listItem.ForeColor = Color.Gray;

            if (monitoredItem.Status.Created)
            {
                listItem.ForeColor = Color.Empty;

                if ((revisedQueueSize != monitoredItem.QueueSize) && monitoredItem.AttributeId != Opc.Ua.Attributes.EventNotifier)
                {
                    listItem.ForeColor = Color.DarkOrange;
                }

                if ((revisedSampingInterval != monitoredItem.SamplingInterval) && monitoredItem.AttributeId != Opc.Ua.Attributes.EventNotifier)
                {
                    listItem.ForeColor = Color.DarkOrange;
                }
            }

            if (monitoredItem.Status.Id == 0)
            {
                listItem.ForeColor = Color.DarkOrange;
            }

            if (monitoredItem.Status.Error != null && ServiceResult.IsBad(monitoredItem.Status.Error))
            {
                listItem.ForeColor = Color.Red;
            }

            if (monitoredItem.AttributesModified)
            {
                listItem.ForeColor = Color.Red;
            }

            listItem.Tag = item;
        }
コード例 #59
0
        public ServiceResult Get(int id)
        {
            ServiceResult service = new ServiceResult();

            return(service);
        }
コード例 #60
0
ファイル: SessionManager.cs プロジェクト: robinson/DataLink
        /// <summary>
        /// Activates an existing session
        /// </summary>
        public virtual bool ActivateSession(
            OperationContext context,
            NodeId authenticationToken,
            SignatureData clientSignature,
            List <SoftwareCertificate> clientSoftwareCertificates,
            ExtensionObject userIdentityToken,
            SignatureData userTokenSignature,
            StringCollection localeIds,
            out byte[]                      serverNonce)
        {
            serverNonce = null;

            Session           session         = null;
            UserIdentityToken newIdentity     = null;
            UserTokenPolicy   userTokenPolicy = null;

            lock (m_lock)
            {
                // find session.
                if (!m_sessions.TryGetValue(authenticationToken, out session))
                {
                    throw new ServiceResultException(StatusCodes.BadSessionClosed);
                }

                // create new server nonce.
                serverNonce = new byte[m_minNonceLength];
                IBuffer buffer = CryptographicBuffer.GenerateRandom((uint)m_minNonceLength);
                CryptographicBuffer.CopyToByteArray(buffer, out serverNonce);

                // validate before activation.
                session.ValidateBeforeActivate(
                    context,
                    clientSignature,
                    clientSoftwareCertificates,
                    userIdentityToken,
                    userTokenSignature,
                    localeIds,
                    serverNonce,
                    out newIdentity,
                    out userTokenPolicy);
            }

            IUserIdentity identity          = null;
            IUserIdentity effectiveIdentity = null;
            ServiceResult error             = null;

            try
            {
                // check if the application has a callback which validates the identity tokens.
                lock (m_eventLock)
                {
                    if (m_ImpersonateUser != null)
                    {
                        ImpersonateEventArgs args = new ImpersonateEventArgs(newIdentity, userTokenPolicy);
                        m_ImpersonateUser(session, args);

                        if (ServiceResult.IsBad(args.IdentityValidationError))
                        {
                            error = args.IdentityValidationError;
                        }
                        else
                        {
                            identity          = args.Identity;
                            effectiveIdentity = args.EffectiveIdentity;
                        }
                    }
                }

                // parse the token manually if the identity is not provided.
                if (identity == null)
                {
                    identity = new UserIdentity(newIdentity);
                }

                // use the identity as the effectiveIdentity if not provided.
                if (effectiveIdentity == null)
                {
                    effectiveIdentity = identity;
                }
            }
            catch (Exception e)
            {
                if (e is ServiceResultException)
                {
                    throw;
                }

                throw ServiceResultException.Create(
                          StatusCodes.BadIdentityTokenInvalid,
                          e,
                          "Could not validate user identity token: {0}",
                          newIdentity);
            }

            // check for validation error.
            if (ServiceResult.IsBad(error))
            {
                throw new ServiceResultException(error);
            }

            // activate session.
            bool contextChanged = session.Activate(
                context,
                clientSoftwareCertificates,
                newIdentity,
                identity,
                effectiveIdentity,
                localeIds,
                serverNonce);

            // raise session related event.
            if (contextChanged)
            {
                RaiseSessionEvent(session, SessionEventReason.Activated);
            }

            // indicates that the identity context for the session has changed.
            return(contextChanged);
        }