public async Task <InsertTransactionResponse> AddAsync(InsertTransactionRequest request, ClaimsPrincipal claimsPrincipal)
        {
            InsertTransactionResponse response = new InsertTransactionResponse();

            try
            {
                //TODO: Validate if a the user can add transactions

                if (request.Transaction.Amount <= 0)
                {
                    response.IsSuccessful = false;
                    response.Errors.Add(new Error()
                    {
                        Code = ((int)ErrorCodes.InvalidAmount).ToString(), Message = "The amount is invalid"
                    });
                    return(response);
                }

                var fromAccount = await this.accountRepository.GetAsync(request.Transaction.FromAccountId).ConfigureAwait(false);


                if (fromAccount.IsNull())
                {
                    response.IsSuccessful = false;
                    response.Errors.Add(new Error()
                    {
                        Code = ((int)ErrorCodes.NotFound).ToString(), Message = $"Account {request.Transaction.FromAccountId} was not found"
                    });
                    return(response);
                }

                var toAccount = await this.accountRepository.GetAsync(request.Transaction.ToAccountId).ConfigureAwait(false);


                if (toAccount.IsNull())
                {
                    response.IsSuccessful = false;
                    response.Errors.Add(new Error()
                    {
                        Code = ((int)ErrorCodes.NotFound).ToString(), Message = $"Account {request.Transaction.ToAccountId} was not found"
                    });
                    return(response);
                }



                var user = await this.userRepository.GetByIdAsync(request.Transaction.UserId);

                //TODO: Check if user can register transactions

                var transactionID = await this.transactionRepository.AddAsync(CreateTransaction(request));

                if (fromAccount.Balance.Available >= request.Transaction.Amount)
                {
                    var transaction = await this.GetTransactionAsync(transactionID);

                    transaction.ChangeStatus(TransactionStatus.Processed)
                    .UpdateAmount(request.Transaction.Amount)
                    .SetProcessingDate(SystemTime.Now());

                    await this.transactionRepository.UpdateAsync(transaction, fromAccount, toAccount);
                }
                else
                {
                    var transaction = await this.GetTransactionAsync(transactionID);

                    transaction.ChangeStatus(TransactionStatus.Rejected)
                    .UpdateAmount(null)
                    .SetProcessingDate(SystemTime.Now());

                    await this.transactionRepository.UpdateAsync(transaction);

                    response.IsSuccessful = false;
                    response.Errors.Add(new Error()
                    {
                        Code = ((int)ErrorCodes.InsufficientFunds).ToString(), Message = "The available balance is not enough to make the transaction"
                    });
                    return(response);
                }

                response.Transaction = await this.GetTransactionAsync(transactionID);
            }
            catch (Exception)
            {
                response.IsSuccessful = false;
                response.Errors.Add(new Error()
                {
                    Code = ((int)ErrorCodes.Unknown).ToString(), Message = "There was a problem. Please try again later"
                });
            }

            return(response);
        }
 public void IsNotInPast_With_One_Second_Ago_Should_Throw_Exception()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => Check.Argument.IsNotInPast(SystemTime.Now().AddSeconds(-1), "OneSecondAgo"));
 }
 public void IsNotInFuture_With_One_Second_After_Should_Throw_Exception()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => Check.Argument.IsNotInFuture(SystemTime.Now().AddSeconds(1), "OneSecondAfter"));
 }
        public ProcessResult Validate(MessageContext context)
        {
            if (context == null)
            {
                return(new ProcessResult(false, Status.NoneCommand, "空命令"));
            }
            MessageType type = context.Command.MessageType;

            #region 非法的表述类型
            if (type == MessageType.Undefined ||
                type == default(MessageType))
            {
                return(new ProcessResult(false, Status.InvalidMessageType, "非法的表述类型"));
            }
            #endregion
            #region 验证事件
            if (type == MessageType.Event)
            {
                #region 非法的事件源类型
                EventSourceType eventSourceType;
                if (!context.Command.EventSourceType.TryParse(out eventSourceType) ||
                    eventSourceType == EventSourceType.Invalid ||
                    eventSourceType == default(EventSourceType))
                {
                    return(new ProcessResult(false, Status.InvalidEventSourceType, "非法的事件源类型"));
                }
                #endregion
                #region 非法的事件主题码
                if (!EventSubjectCode.Contains(context.Command.EventSubjectCode))
                {
                    return(new ProcessResult(false, Status.InvalidEventSubject, "非法的事件主题码"));
                }
                #endregion
                #region 非法的状态码或原因短语
                Status outStateCode;
                if (!context.Command.Status.TryParse(out outStateCode))
                {
                    return(new ProcessResult(false, Status.InvalidStatus, "非法的状态码"));
                }
                if (!string.IsNullOrEmpty(context.Command.ReasonPhrase) &&
                    context.Command.ReasonPhrase.Length > 50)
                {
                    return(new ProcessResult(false, Status.OutOfLength, "原因短语超过50个字符长度"));
                }
                #endregion
                #region 本节点分发的命令的请求标识是Guid型的

                if (eventSourceType == EventSourceType.Command)
                {
                    Guid requestId;
                    if (!Guid.TryParse(context.Command.MessageId, out requestId))
                    {
                        return(new ProcessResult(false, Status.InvalidArgument, @"参数MessageID错误:服务端的请求标识是Guid类型的。当EventSourceType取值Command时该MessageID是服务端分发该条命令时使用的MessageId"));
                    }
                }

                #endregion
            }
            #endregion
            #region 发起人验证
            if (!string.IsNullOrEmpty(context.Command.UserName) && context.Command.UserName.Length > 50)
            {
                return(new ProcessResult(false, Status.OutOfLength, "发起人超过最大50个字符长度。一条命令至多由一个人发起,这个人就是责任人,不存在联名发起命令一说。"));
            }
            #endregion
            #region 时间戳验证
            if (context.Command.TimeStamp < SystemTime.Now().AddYears(-1) || // TODO:配置消息的左时间
                context.Command.TimeStamp > SystemTime.Now().AddSeconds(context.Host.Config.TicksTimeout))
            {
                return(new ProcessResult(false, Status.InvalidCommandTicks, "非法的命令时间戳,命令时间戳不能是一年前或将来。"));
            }
            #endregion
            #region 客户端类型验证
            if (context.Command.ClientType == ClientType.Undefined)
            {
                return(new ProcessResult(false, Status.InvalidClientType, "非法的客户端类型"));
            }
            #endregion
            #region 节点验证
            NodeDescriptor requestNode = null;
            if (context.Command.ClientType == ClientType.Node)
            {
                if (!context.Host.NodeHost.Nodes.TryGetNodeById(context.Command.ClientId, out requestNode))
                {
                    return(new ProcessResult(false, Status.InvalidClientId, "非法的节点"));
                }
            }
            #endregion
            #region 本体码验证
            if (string.IsNullOrEmpty(context.Command.Ontology))
            {
                return(new ProcessResult(false, Status.InvalidOntology, "必须通过本体码界定命令的上下文,本体码不能为空。"));
            }
            OntologyDescriptor ontology;
            if (!context.Host.NodeHost.Ontologies.TryGetOntology(context.Command.Ontology, out ontology))
            {
                return(new ProcessResult(false, Status.InvalidOntology, "非法的本体码。本体列表中不存在编码为" + context.Ontology + "的本体码"));
            }
            if (ontology.Ontology.IsEnabled != 1)
            {
                return(new ProcessResult(false, Status.InvalidOntology, "该本体已被禁用"));
            }
            #endregion
            #region 动作码验证
            if (string.IsNullOrEmpty(context.Command.Verb.Code))
            {
                return(new ProcessResult(false, Status.InvalidVerb, "必须通过本体动作码来表明您的命令是要做什么,本体动作码不能为空。"));
            }
            if (!ontology.Actions.ContainsKey(context.Command.Verb))
            {
                return(new ProcessResult(false, Status.InvalidVerb, "非法的动作码," + ontology.Ontology.Name + "未定义编码为" + context.Command.Verb + "的动作"));
            }
            if (context.Command.ClientType == ClientType.Node)
            {
                var nodeActions = requestNode.Node.NodeActions;
                if (!nodeActions.ContainsKey(ontology) || !nodeActions[ontology].ContainsKey(context.Command.Verb))
                {
                    return(new ProcessResult(false, Status.NoPermission, "您的节点没有" + ontology.Actions[context.Command.Verb].Name + ontology.Ontology.Name + "的权限"));
                }
            }
            #endregion
            #region 本体元素码验证器
            if (context.Command.DataTuple.IdItems == null || context.Command.DataTuple.IdItems.IsEmpty)
            {
                return(new ProcessResult(false, Status.InvalidInfoId, "信息标识不能为空"));
            }
            var elementDic      = ontology.Elements;
            var failDescription = new List <DataItem>();
            var infoIdItems     = new List <InfoItem>();
            if (context.Command.DataTuple.IdItems != null)
            {
                foreach (var item in context.Command.DataTuple.IdItems.Items)
                {
                    if (item.Key == null || !elementDic.ContainsKey(item.Key) || elementDic[item.Key].Element.IsEnabled != 1)
                    {
                        failDescription.Add(item);
                    }
                    else
                    {
                        infoIdItems.Add(InfoItem.Create(elementDic[item.Key], item.Value));
                    }
                }
            }
            var infoValueItems = new List <InfoItem>();
            if (context.Command.DataTuple.ValueItems != null)
            {
                foreach (var item in context.Command.DataTuple.ValueItems.Items)
                {
                    if (item.Key != null && !elementDic.ContainsKey(item.Key))
                    {
                        failDescription.Add(item);
                    }
                    else
                    {
                        infoValueItems.Add(InfoItem.Create(elementDic[item.Key], item.Value));
                    }
                }
            }
            if (failDescription.Count > 0)
            {
                return(new ProcessResult(false, Status.InvalidElement, "非法的本体元素码" + failDescription[0].Key));
            }
            #endregion
            #region 信息标识验证
            if (context.Command.DataTuple.IdItems.IsEmpty)
            {
                return(new ProcessResult(false, Status.InvalidInfoId, "非法的信息标识"));
            }
            else if (ontology.Ontology.IsCataloguedEntity)
            {
                if (Verb.Create.Equals(context.Command.Verb) &&
                    type != MessageType.Event)
                {
                    if (requestNode != context.Host.NodeHost.Nodes.CenterNode &&
                        context.Command.DataTuple.IdItems.Items.Any(a => string.Equals(a.Key, "Id", StringComparison.OrdinalIgnoreCase)))
                    {
                        return(new ProcessResult(false, Status.InvalidInfoId, "非中心节点的create型命令不能提供Id"));
                    }
                    else if ((ontology.Ontology.IsCataloguedEntity &&
                              !context.Command.DataTuple.IdItems.Items.Any(a => string.Equals(a.Key, "ZZJGM", StringComparison.OrdinalIgnoreCase))) ||
                             !context.Command.DataTuple.IdItems.Items.Any(a => string.Equals(a.Key, "XM", StringComparison.OrdinalIgnoreCase)))
                    {
                        return(new ProcessResult(false, Status.InvalidInfoId, "没有提供姓名或目录"));
                    }
                }
            }
            #endregion
            #region 信息标识项验证
            ProcessResult result;
            foreach (var infoItem in infoIdItems)
            {
                if (!this.ValidInfoItem(infoItem, out result))
                {
                    return(result);
                }
            }
            #endregion
            #region 信息值项验证
            if (Verb.Create.Equals(context.Command.Verb) ||
                Verb.Update.Equals(context.Command.Verb))
            {
                if (context.Command.DataTuple.ValueItems.IsEmpty)
                {
                    return(new ProcessResult(false, Status.InvalidInfoValue, "Create和Update型动作必须提供InfoValue输入"));
                }
                foreach (var infoItem in infoValueItems)
                {
                    if (!this.ValidInfoItem(infoItem, out result))
                    {
                        return(result);
                    }
                }
            }
            #endregion

            return(new ProcessResult(true, Status.Ok, "命令输入验证通过"));
        }
        public void Setup()
        {
            settings.Waybills.Add(new WaybillSettings(user, address));
            session.DeleteEach <Stock>();
            session.DeleteEach <BarcodeProducts>();
            model   = Open(new Frontend2());
            catalog = session.Query <Catalog>().First();
            stock   = new Stock()
            {
                Product          = catalog.FullName,
                CatalogId        = catalog.Id,
                Status           = StockStatus.Available,
                RejectStatus     = RejectStatus.NotDefective,
                Address          = address,
                RetailCost       = 1,
                Quantity         = 5,
                ReservedQuantity = 0,
                Barcode          = "10",
                ProductId        = 1,
                Exp = SystemTime.Now()
            };
            stateless.Insert(stock);

            var product1     = GetProduct("АЦЕТИЛСАЛИЦИЛОВАЯ КИСЛОТА табл. 0.5 г N10");
            var stockForList = new Stock(session, product1, address, StockStatus.Available, 133)
            {
                Quantity = 5,
                Barcode  = "4605635002748",
                Exp      = SystemTime.Now()
            };

            stateless.Insert(stockForList);

            var product2 = GetProduct("АЦЕТИЛСАЛИЦИЛОВАЯ КИСЛОТА табл. 0.5г N20");

            stockForList = new Stock(session, product2, address, StockStatus.Available, 132)
            {
                Quantity = 5,
                Barcode  = "4605635002748",
                Exp      = SystemTime.Now()
            };
            stateless.Insert(stockForList);

            var products = new[] {
                GetProduct("АСПИРИН БАЙЕР табл. 100мг N20"),
                GetProduct("АСПИРИН БАЙЕР табл. 500 мг N10"),
                GetProduct("АСПИРИН БАЙЕР табл. 500 мг N10"),
            };

            for (int i = 0; i < 3; i++)
            {
                stockForList = new Stock(session, products[i], address, StockStatus.Available, 132)
                {
                    Address  = address,
                    Quantity = 2 + i,
                };
                stateless.Insert(stockForList);
            }

            BarcodeProduct = new BarcodeProducts()
            {
                Product  = product1,
                Producer = session.Query <Producer>().First(),
                Barcode  = "30"
            };
            stateless.Insert(BarcodeProduct);

            session.DeleteEach <Check>();
            session.Flush();
        }
示例#6
0
 public TestEvent(Categorisation categorisation, Timings timings) : base(SystemTime.Now(), categorisation, timings)
 {
 }
示例#7
0
 /// <summary>
 /// Registers this draw as drawn
 /// </summary>
 public void RegisterAsDrawn()
 {
     DrawDate = SystemTime.Now();
 }
        public ActionResult Login(string userNameOrEmail, string password, bool?rememberMe)
        {
            JsonViewData viewData = Validate <JsonViewData>(
                new Validation(() => string.IsNullOrEmpty(userNameOrEmail.NullSafe()), "Nazwa użytkownika/e-mail nie może być pusty."),
                new Validation(() => string.IsNullOrEmpty(password.NullSafe()), "Hasło nie może być puste.")
                );

            if (viewData == null)
            {
                try
                {
                    using (IUnitOfWork unitOfWork = UnitOfWork.Begin())
                    {
                        IUser user = userNameOrEmail.IsEmail() == false?
                                     UserRepository.FindByUserName(userNameOrEmail.Trim()) :
                                         UserRepository.FindByEmail(userNameOrEmail.Trim());

                        if (user != null)
                        {
                            if (!user.IsActive)
                            {
                                string userId = user.Id.Shrink();

                                string url = string.Concat(Settings.RootUrl, Url.RouteUrl("Activate", new { id = userId }));

                                _emailSender.SendRegistrationInfo(user.Email, user.UserName, password, url);
                            }

                            viewData = Validate <JsonViewData>(
                                new Validation(() => user.IsLockedOut, "Twoje konto jest aktualnie zablokowane. Skontaktuj się z pomocą aby rozwiązać ten problem."),
                                new Validation(() => !user.IsActive, "Twoje konto nie zostało jeszcze aktywowane. Na Twoją skrzynkę e-mail wysłano ponownie link aktywacyjny."),
                                new Validation(() => user.IsOpenIDAccount(), "Podany login jest poprawny tylko z OpenID.")
                                );

                            if (viewData == null)
                            {
                                if (string.Compare(user.Password, password.Trim().Hash(), StringComparison.OrdinalIgnoreCase) == 0)
                                {
                                    user.LastActivityAt = SystemTime.Now();
                                    unitOfWork.Commit();

                                    FormsAuthentication.SetAuthCookie(user.UserName, rememberMe ?? false);
                                    viewData = new JsonViewData {
                                        isSuccessful = true
                                    };

                                    Log.Info("Użytkownik zalogowany: {0}", user.UserName);
                                }
                            }
                        }

                        if (viewData == null)
                        {
                            viewData = new JsonViewData {
                                errorMessage = "Niepoprawne dane logowania."
                            };
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Exception(e);
                    viewData = new JsonViewData {
                        errorMessage = FormatStrings.UnknownError.FormatWith("logowania")
                    };
                }
            }

            return(Json(viewData));
        }
示例#9
0
 /// <summary>
 /// Check if date is in the past
 /// </summary>
 /// <param name="instance"></param>
 /// <returns></returns>
 public static bool IsInPast(this DateTime instance)
 {
     return(instance < SystemTime.Now());
 }
示例#10
0
        private void FindScoreById()
        {
            _innerRepository.Setup(r => r.FindScoreById(It.IsAny <Guid>(), It.IsAny <DateTime>(), It.IsAny <DateTime>())).Returns(100).Verifiable();
            log.Setup(l => l.Info(It.IsAny <string>())).Verifiable();

            _loggingRepository.FindScoreById(Guid.NewGuid(), SystemTime.Now().AddHours(-4), SystemTime.Now());
        }
        public ActionResult OpenId(string identifier, bool?rememberMe)
        {
            string errorMessage = null;

            string url = string.Concat(Settings.RootUrl, Url.Content("~/xrds.axd"));

            HttpContext.Response.Headers.Add("X-XRDS-Location", url);

            try
            {
                if (OpenIdRelyingParty.Response == null)
                {
                    if (!string.IsNullOrEmpty(identifier))
                    {
                        Identifier id;

                        if (Identifier.TryParse(identifier, out id))
                        {
                            var realm = new Realm(new Uri(string.Concat(Settings.RootUrl, Url.RouteUrl("OpenId"))));

                            IAuthenticationRequest request = OpenIdRelyingParty.CreateRequest(identifier, realm);

                            var fetch = new ClaimsRequest
                            {
                                Email = DemandLevel.Require
                            };

                            request.AddExtension(fetch);

                            OpenIdRememberMe = rememberMe ?? false;
                            ReturnUrl        = (HttpContext.Request.UrlReferrer != null) ? HttpContext.Request.UrlReferrer.ToString() : string.Empty;

                            return(request.RedirectingResponse.AsActionResult()); //.RedirectToProvider();
                        }
                    }

                    return(new EmptyResult());
                }

                if (OpenIdRelyingParty.Response.Status == AuthenticationStatus.Authenticated)
                {
                    string userName = OpenIdRelyingParty.Response.ClaimedIdentifier;

                    using (IUnitOfWork unitOfWork = UnitOfWork.Begin())
                    {
                        IUser user = UserRepository.FindByUserName(userName);

                        if ((user != null) && user.IsLockedOut)
                        {
                            errorMessage = "Twoje konto jest obecnie zablokowane. Skontaktuj się z nami w tej sprawie.";
                        }
                        else
                        {
                            var fetch = OpenIdRelyingParty.Response.GetExtension <ClaimsResponse>();

                            // Some of the Provider does not return Email
                            // Such as Yahoo, Blogger, Bloglines etc, in that case we will assign a default
                            // email
                            string email = ((fetch == null) || string.IsNullOrEmpty(fetch.Email)) ? Settings.DefaultEmailOfOpenIdUser : fetch.Email;

                            if (user == null)
                            {
                                user = _factory.CreateUser(userName, email, null);
                                UserRepository.Add(user);
                                _eventAggregator.GetEvent <UserActivateEvent>().Publish(new UserActivateEventArgs(user));
                            }
                            else
                            {
                                //Sync the email from OpenID provider.
                                if ((string.Compare(email, user.Email, StringComparison.OrdinalIgnoreCase) != 0) &&
                                    (string.Compare(email, Settings.DefaultEmailOfOpenIdUser, StringComparison.OrdinalIgnoreCase) != 0))
                                {
                                    user.ChangeEmail(email);
                                }
                            }

                            user.LastActivityAt = SystemTime.Now();

                            unitOfWork.Commit();
                            FormsAuthentication.SetAuthCookie(userName, OpenIdRememberMe);
                        }
                    }
                }
                else if ((OpenIdRelyingParty.Response.Status == AuthenticationStatus.Failed) || (OpenIdRelyingParty.Response.Status == AuthenticationStatus.Canceled))
                {
                    if (OpenIdRelyingParty.Response.Exception != null)
                    {
                        errorMessage = OpenIdRelyingParty.Response.Exception.Message;
                    }
                    if (String.IsNullOrEmpty(errorMessage))
                    {
                        errorMessage = "Nie udało się zalogować przez wybranego dostawcę OpenID.";
                    }
                }
            }
            catch (Exception oid)
            {
                errorMessage = oid.Message;
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                GenerateMessageCookie(errorMessage, true);
            }

            string returnUrl = ReturnUrl;

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(RedirectToRoute("Published"));
        }
示例#12
0
        public void Calculate_Should_Return_Correct_Weight_For_All_Combination()
        {
            var story = Setup("192.168.0.1", "192.168.0.1", "192.168.0.2");

            Assert.Equal((OwnerScore + SameIpScore + DifferentIpScore), _strategy.Calculate(SystemTime.Now(), story.Object));
        }
示例#13
0
        public void Calculate_Should_Return_Correct_Weight_For_Different_IPAddress()
        {
            var story = Setup("192.168.0.1", "192.168.0.2", "192.168.0.3");

            Assert.Equal(OwnerScore + (DifferentIpScore * 2), _strategy.Calculate(SystemTime.Now(), story.Object));
        }
示例#14
0
        public void Calculate_Should_Return_Correct_Weight_For_Author()
        {
            var story = Setup("192.168.0.1");

            Assert.Equal(OwnerScore, _strategy.Calculate(SystemTime.Now(), story.Object));
        }
示例#15
0
 public void Cleanup()
 {
     SystemTime.Freeze(SystemTime.Now());
 }
示例#16
0
 /// <summary>
 /// Check if date is in the future
 /// </summary>
 /// <param name="instance"></param>
 /// <returns></returns>
 public static bool IsInFuture(this DateTime instance)
 {
     return(instance > SystemTime.Now());
 }
示例#17
0
 public TestEvent(Categorisation categorisation)
     : base(SystemTime.Now(), categorisation, new Timings(0))
 {
 }
示例#18
0
        public void IsApproved_Should_Be_True_When_Aapproved_Is_Not_Null()
        {
            _story.SetupGet(s => s.ApprovedAt).Returns(SystemTime.Now());

            Assert.True(_story.Object.IsApproved());
        }
示例#19
0
 public TestEvent() : base(SystemTime.Now(),
                           new Categorisation("Category", "SubCategory"), new Timings(0))
 {
 }
示例#20
0
        public void Execute(RequestData <Tuple <IItemInstance, UseItemPacket> > requestData)
        {
            requestData.ClientSession.SendPacket(requestData.ClientSession.Character.GenerateEff(123));

            var itemInstance = requestData.Data.Item1;
            var packet       = requestData.Data.Item2;

            if (requestData.ClientSession.Character.InExchangeOrShop)
            {
                _logger.Error(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.CANT_USE_ITEM_IN_SHOP));
                return;
            }

            if (itemInstance.BoundCharacterId == null)
            {
                if (packet.Mode == 0 && itemInstance.Item.RequireBinding)
                {
                    requestData.ClientSession.SendPacket(
                        new QnaPacket
                    {
                        YesPacket = requestData.ClientSession.Character.GenerateUseItem(itemInstance.Type,
                                                                                        itemInstance.Slot, (byte)packet.Mode, (byte)packet.Parameter),
                        Question = requestData.ClientSession.GetMessageFromKey(LanguageKey.ASK_BIND)
                    });
                    return;
                }

                if (packet.Mode != 0)
                {
                    itemInstance.BoundCharacterId = requestData.ClientSession.Character.CharacterId;
                }
            }

            if (itemInstance.Item.LevelMinimum > (itemInstance.Item.IsHeroic
                    ? requestData.ClientSession.Character.HeroLevel : requestData.ClientSession.Character.Level) ||
                itemInstance.Item.Sex != 0 &&
                ((itemInstance.Item.Sex >> (byte)requestData.ClientSession.Character.Gender) & 1) != 1 ||
                itemInstance.Item.Class != 0 &&
                ((itemInstance.Item.Class >> (byte)requestData.ClientSession.Character.Class) & 1) != 1)
            {
                requestData.ClientSession.SendPacket(
                    requestData.ClientSession.Character.GenerateSay(
                        requestData.ClientSession.GetMessageFromKey(LanguageKey.BAD_EQUIPMENT),
                        Shared.Enumerations.SayColorType.Yellow));
                return;
            }

            if (requestData.ClientSession.Character.UseSp && itemInstance.Item.EquipmentSlot == EquipmentType.Fairy)
            {
                var sp = requestData.ClientSession.Character.Inventory.LoadBySlotAndType <IItemInstance>(
                    (byte)EquipmentType.Sp, PocketType.Wear);

                if (sp != null && sp.Item.Element != 0 && itemInstance.Item.Element != sp.Item.Element &&
                    itemInstance.Item.Element != sp.Item.SecondaryElement)
                {
                    requestData.ClientSession.SendPacket(new MsgPacket
                    {
                        Message = Language.Instance.GetMessageFromKey(LanguageKey.BAD_FAIRY,
                                                                      requestData.ClientSession.Account.Language)
                    });
                    return;
                }
            }

            if (itemInstance.Item.EquipmentSlot == EquipmentType.Sp)
            {
                double timeSpanSinceLastSpUsage =
                    (SystemTime.Now() - requestData.ClientSession.Character.LastSp).TotalSeconds;
                var sp = requestData.ClientSession.Character.Inventory.LoadBySlotAndType <IItemInstance>(
                    (byte)EquipmentType.Sp, PocketType.Wear);
                if (timeSpanSinceLastSpUsage < requestData.ClientSession.Character.SpCooldown && sp != null)
                {
                    requestData.ClientSession.SendPacket(new MsgPacket
                    {
                        Message = string.Format(Language.Instance.GetMessageFromKey(LanguageKey.SP_INLOADING,
                                                                                    requestData.ClientSession.Account.Language),
                                                requestData.ClientSession.Character.SpCooldown - (int)Math.Round(timeSpanSinceLastSpUsage))
                    });
                    return;
                }

                if (requestData.ClientSession.Character.UseSp)
                {
                    requestData.ClientSession.SendPacket(
                        requestData.ClientSession.Character.GenerateSay(
                            requestData.ClientSession.GetMessageFromKey(LanguageKey.SP_BLOCKED),
                            Shared.Enumerations.SayColorType.Yellow));
                    return;
                }

                if (itemInstance.Rare == -2)
                {
                    requestData.ClientSession.SendPacket(new MsgPacket
                    {
                        Message = Language.Instance.GetMessageFromKey(LanguageKey.CANT_EQUIP_DESTROYED_SP,
                                                                      requestData.ClientSession.Account.Language)
                    });
                    return;
                }
            }

            if (requestData.ClientSession.Character.JobLevel < itemInstance.Item.LevelJobMinimum)
            {
                requestData.ClientSession.SendPacket(
                    requestData.ClientSession.Character.GenerateSay(
                        requestData.ClientSession.GetMessageFromKey(LanguageKey.LOW_JOB_LVL),
                        Shared.Enumerations.SayColorType.Yellow));
                return;
            }

            requestData.ClientSession.Character.Inventory.MoveInPocket(packet.Slot, packet.Type, PocketType.Wear,
                                                                       (short)itemInstance.Item.EquipmentSlot, true);
            var newItem =
                requestData.ClientSession.Character.Inventory
                .LoadBySlotAndType <IItemInstance>(packet.Slot, packet.Type);

            requestData.ClientSession.SendPacket(newItem.GeneratePocketChange(packet.Type, packet.Slot));

            requestData.ClientSession.Character.MapInstance.Sessions.SendPacket(requestData.ClientSession.Character
                                                                                .GenerateEq());
            requestData.ClientSession.SendPacket(requestData.ClientSession.Character.GenerateEquipment());

            if (itemInstance.Item.EquipmentSlot == EquipmentType.Sp)
            {
                requestData.ClientSession.SendPacket(requestData.ClientSession.Character.GenerateSpPoint());
            }

            if (itemInstance.Item.EquipmentSlot == EquipmentType.Fairy)
            {
                requestData.ClientSession.Character.MapInstance.Sessions.SendPacket(
                    requestData.ClientSession.Character.GeneratePairy(itemInstance as WearableInstance));
            }

            if (itemInstance.Item.EquipmentSlot == EquipmentType.Amulet)
            {
                requestData.ClientSession.SendPacket(requestData.ClientSession.Character.GenerateEff(39));
            }


            if (itemInstance.Item.ItemValidTime > 0 && itemInstance.BoundCharacterId != null)
            {
                itemInstance.ItemDeleteTime = SystemTime.Now().AddSeconds(itemInstance.Item.ItemValidTime);
            }

            if (itemInstance.Item.RequireBinding)
            {
                itemInstance.BoundCharacterId = requestData.ClientSession.Character.CharacterId;
            }
        }
示例#21
0
        public override async Task ExecuteAsync(CSkillPacket packet, ClientSession clientSession)
        {
            var medalBonus = clientSession.Character.StaticBonusList.FirstOrDefault(s =>
                                                                                    (s.StaticBonusType == StaticBonusType.BazaarMedalGold) ||
                                                                                    (s.StaticBonusType == StaticBonusType.BazaarMedalSilver));

            if (medalBonus != null)
            {
                var medal = medalBonus.StaticBonusType == StaticBonusType.BazaarMedalGold ? (byte)MedalType.Gold
                    : (byte)MedalType.Silver;
                var time = (int)(medalBonus.DateEnd == null ? 720 : ((TimeSpan)(medalBonus.DateEnd - SystemTime.Now())).TotalHours);
                await clientSession.SendPacketAsync(new MsgPacket
                {
                    Message = GameLanguage.Instance.GetMessageFromKey(LanguageKey.INFO_BAZAAR,
                                                                      clientSession.Account.Language),
                    Type = MessageType.Whisper
                }).ConfigureAwait(false);

                await clientSession.SendPacketAsync(new WopenPacket
                {
                    Type     = WindowType.NosBazaar,
                    Unknown  = medal,
                    Unknown2 = (byte)time
                }).ConfigureAwait(false);
            }
            else
            {
                await clientSession.SendPacketAsync(new InfoPacket
                {
                    Message = GameLanguage.Instance.GetMessageFromKey(LanguageKey.NO_BAZAAR_MEDAL,
                                                                      clientSession.Account.Language)
                }).ConfigureAwait(false);
            }
        }
示例#22
0
        public static bool HasCreatedMessageAndNotificationToday()
        {
            DateTime lastRiskAlertUtc = GetDateTimeFromSecureStorageForKey(SecureStorageKeys.LAST_HIGH_RISK_ALERT_UTC_KEY, nameof(HasCreatedMessageAndNotificationToday));

            return(lastRiskAlertUtc.Date == SystemTime.Now().Date);
        }
示例#23
0
        public Task ExecuteAsync(RequestData <Tuple <IAliveEntity, NrunPacket> > requestData)
        {
            var medalBonus = requestData.ClientSession.Character.StaticBonusList
                             .FirstOrDefault(s =>
                                             (s.StaticBonusType == StaticBonusType.BazaarMedalGold) ||
                                             (s.StaticBonusType == StaticBonusType.BazaarMedalSilver));
            var medal = medalBonus != null ? medalBonus.StaticBonusType == StaticBonusType.BazaarMedalGold
                ? (byte)MedalType.Gold : (byte)MedalType.Silver : (byte)0;
            var time = medalBonus != null ? (int)(medalBonus.DateEnd == null ? 720 : ((TimeSpan)(medalBonus.DateEnd - SystemTime.Now())).TotalHours) : 0;

            return(requestData.ClientSession.SendPacketAsync(new WopenPacket
            {
                Type = WindowType.NosBazaar,
                Unknown = medal,
                Unknown2 = (byte)time
            }));
        }
示例#24
0
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            if (!Debugger.IsAttached)
            {
                Observable.Interval(TimeSpan.FromSeconds(2)).Subscribe(_ => MasterClientListSingleton.Instance.Channels
                                                                       .Where(s =>
                                                                              (s.LastPing.AddSeconds(10) < SystemTime.Now()) && (s.WebApi != null)).Select(s => s.Id).ToList()
                                                                       .ForEach(id =>
                {
                    _logger.Warning(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.CONNECTION_LOST),
                                    id.ToString());
                    MasterClientListSingleton.Instance.Channels.RemoveAll(s => s.Id == id);
                }));
            }

            _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.SUCCESSFULLY_LOADED));
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Console.Title += $@" - WebApi : {_masterConfiguration.WebApi}";
            }

            return(Task.CompletedTask);
        }
 public void IsNotInvalidDate_With_Current_Date_Should_Not_Throw_Exception()
 {
     Assert.DoesNotThrow(() => Check.Argument.IsNotInvalidDate(SystemTime.Now(), "Now"));
 }
示例#26
0
        public void Calculate_Should_Return_Correct_Weight_For_Same_Ip()
        {
            var story = Setup("192.168.0.1", "192.168.0.1", "192.168.0.1");

            Assert.Equal((SameIpWeight * 2), _strategy.Calculate(SystemTime.Now(), story.Object));
        }
 public void IsNotInPast_With_OneSecond_After_Should_Not_Throw_Exception()
 {
     Assert.DoesNotThrow(() => Check.Argument.IsNotInPast(SystemTime.Now().AddSeconds(1), "OneSecondAfter"));
 }
示例#28
0
        public void Calculate_Should_Return_Correct_Weight_For_Both_Ips()
        {
            var story = Setup("192.168.0.1", "192.168.0.1", "192.168.0.2");

            Assert.Equal((SameIpWeight + DifferentIpWeight), _strategy.Calculate(SystemTime.Now(), story.Object));
        }
 public void IsNotInFuture_With_OneSecond_Ago_Should_Not_Throw_Exception()
 {
     Assert.DoesNotThrow(() => Check.Argument.IsNotInFuture(SystemTime.Now().AddSeconds(-1), "OneSecondAgo"));
 }
示例#30
0
        public static Recording CreateFakeRecording()
        {
            var recording = new Recording
            {
                Actions  = new List <IRecordedAction>(),
                FilePath = @"FakePath:\FakeDirectory\FakeRecording.txt",
                Date     = SystemTime.Now(),
                Zones    = new List <ClickZone>
                {
                    new ClickZone()
                    {
                        Shape = new Rectangle(100, 200, 50, 51)
                    }
                }
            };

            recording.Actions.Add(new RecordedMouseButtonPress()
            {
                Id = 1, PixelColor = Color.Blue, Button = MouseButtons.Left, Date = SystemTime.Now().AddSeconds(-5)
            });
            recording.Actions.Add(new RecordedMouseButtonRelease()
            {
                Id = 2, PixelColor = Color.Blue, Button = MouseButtons.Left, Date = SystemTime.Now().AddSeconds(-4)
            });
            recording.Actions.Add(new RecordedKeyboardButtonPress()
            {
                Id = 3, Key = Keys.A, Date = SystemTime.Now().AddSeconds(-3)
            });
            recording.Actions.Add(new RecordedKeyboardButtonRelease()
            {
                Id = 4, Key = Keys.A, Date = SystemTime.Now().AddSeconds(-2)
            });
            recording.Actions.Add(new RecordedMouseMove()
            {
                Id = 5, ScreenCoordinate = new Point(100, 125), PixelColor = Color.Brown, Button = MouseButtons.None, Date = SystemTime.Now().AddSeconds(-1)
            });

            return(recording);
        }