Example #1
0
        public M4PLOrderCreationResponse GenerateOrderInNav(long jobId)
        {
            Order.NavOrderCommands navOrderRepo = new Order.NavOrderCommands();
            string     navAPIURL      = M4PLBusinessConfiguration.NavAPIUrl;
            string     navAPIUserName = M4PLBusinessConfiguration.NavAPIUserName;
            string     navAPIPassword = M4PLBusinessConfiguration.NavAPIPassword;
            long       customerId     = M4PLBusinessConfiguration.ElectroluxCustomerId.ToLong();
            ActiveUser activeUser     = ActiveUser;
            M4PLOrderCreationResponse m4PLOrderCreationResponse = new M4PLOrderCreationResponse();
            List <Task> tasks = new List <Task>();

            tasks.Add(Task.Factory.StartNew(() =>
            {
                try
                {
                    m4PLOrderCreationResponse.M4PLSalesOrderCreationResponse = navOrderRepo.GenerateSalesOrderInNav(jobId, navAPIURL, navAPIUserName, navAPIPassword, customerId, activeUser);
                }
                catch (Exception exp)
                {
                    DataAccess.Logger.ErrorLogger.Log(exp, "Error occured while creating the Sales Order for the job", "GenerateOrderInNav", Utilities.Logger.LogType.Error);
                }
            }));

            tasks.Add(Task.Factory.StartNew(() =>
            {
                try
                {
                    m4PLOrderCreationResponse.M4PLPurchaseOrderCreationResponse = navOrderRepo.GeneratePurchaseOrderInNav(jobId, navAPIURL, navAPIUserName, navAPIPassword, customerId, activeUser);
                }
                catch (Exception exp)
                {
                    DataAccess.Logger.ErrorLogger.Log(exp, "Error occured while creating the Purchase Order for the job", "GenerateOrderInNav", Utilities.Logger.LogType.Error);
                }
            }));

            if (tasks.Count > 0)
            {
                Task.WaitAll(tasks.ToArray());
            }

            return(m4PLOrderCreationResponse);
        }
Example #2
0
        public CommunicationResponse DeleteBill([FromBody] DeleteBillRequest deleteBillRequest)
        {
            var response = new CommunicationResponse();

            try
            {
                if (_userService.AuthenticateSession(Request.Headers["Authorization"].ToString()) == false)
                {
                    response.AddError("The authorization credentails were invalid", ErrorCode.SESSION_INVALID);
                    return(response);
                }

                ActiveUser user = _userService.GetUserInformationFromAuthHeader(Request.Headers["Authorization"].ToString());
                if (user.HouseId == 0)
                {
                    response.AddError("You must belong to a household to delete bills", ErrorCode.USER_NOT_IN_HOUSEHOLD);
                    return(response);
                }
                var rowUpdated = _billRepository.DeleteBill(deleteBillRequest.BillId);

                if (rowUpdated == false)
                {
                    response.AddError($"Cannot delete the bill (ID: {deleteBillRequest.BillId}) because it does not exist");
                    return(response);
                }

                response.Notifications = new List <string>
                {
                    $"The bill (ID: {deleteBillRequest.BillId}) has been deleted"
                };
            }
            catch (ErrorCodeException exception)
            {
                response.AddError($"An unexpected exception occured: {exception}", deleteBillRequest, exception.Code);
            }
            catch (Exception exception)
            {
                response.AddError($"An unexpected exception occured: {exception}", deleteBillRequest);
            }

            return(response);
        }
        public ActiveUser CheckLogin(UserViewModel userModel)
        {
            var userData = _repository.Find <User>(x => x.UserName == userModel.UserName && x.Password == userModel.Password && x.Active == true);

            if (userData == null)
            {
                return(null);
            }



            ActiveUser activeUser = new ActiveUser()
            {
                UserId   = userData.UserID,
                Role     = userData.RoleId,
                UserName = userData.UserName,
            };

            return(activeUser);
        }
Example #4
0
        private static void DeleteLineItemInformationForPurchaseOrder(ActiveUser activeUser, List <long> jobIdList, string navAPIUrl, string navAPIUserName, string navAPIPassword, bool isElectronicInvoice, bool allLineItemsUpdated, List <NavPurchaseOrderItemRequest> navPurchaseOrderItemRequest, List <JobOrderItemMapping> jobOrderItemMapping, string poNumber, ref string deleteProFlag, ref bool allLineItemsDeleted, ref bool isRecordDeleted)
        {
            IEnumerable <JobOrderItemMapping> deletedJobOrderItemMapping = null;
            var deletedItems = navPurchaseOrderItemRequest?.Select(s => s.Line_No);

            deletedJobOrderItemMapping = deletedItems == null ? deletedJobOrderItemMapping : jobOrderItemMapping.Where(t => t.IsElectronicInvoiced == isElectronicInvoice && !deletedItems.Contains(t.LineNumber));
            foreach (var deleteItem in deletedJobOrderItemMapping)
            {
                DeletePurchaseOrderItemForNAV(navAPIUrl, navAPIUserName, navAPIPassword, poNumber, deleteItem.LineNumber, out isRecordDeleted);
                if (isRecordDeleted)
                {
                    _commands.DeleteJobOrderItemMapping(deleteItem.JobOrderItemMappingId);
                }

                allLineItemsDeleted = !allLineItemsDeleted ? allLineItemsDeleted : isRecordDeleted;
            }

            deleteProFlag = allLineItemsUpdated ? deleteProFlag : Entities.ProFlag.D.ToString();
            _commands.UpdateJobProFlag(activeUser, deleteProFlag, jobIdList, Entities.EntitiesAlias.PurchaseOrder);
        }
Example #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            au = new ActiveUser
            {
                Password   = opass.Text,
                Login_name = name.Text,
                Newpass    = npass2.Text
            };
            string messageStr = null;

            if (am.ChangePass(au, out messageStr))
            {
                MessageBox.Show("成功");
                this.Hide();
            }
            else
            {
                MessageBox.Show(messageStr);
            }
        }
Example #6
0
        public void SaveActiveUser(int userID, int sessionExpiresMin = 0)
        {
            try
            {
                if (!IsUserTrackAllowed())
                {
                    return;
                }

                ActiveUser activeUser = GetActiveUserByUserID(userID);

                if (activeUser != null)
                {
                    //če v trenutnem dnevu še ni zabeležene prijave se doda nova drugače se posodobijo vrednosti na obstoječi prijavi
                    if (activeUser.LoginDate.Date == DateTime.Today.Date)
                    {
                        activeUser.LoginDate        = DateTime.Now;
                        activeUser.IsActive         = true;
                        activeUser.LastRequestTS    = DateTime.Now;
                        activeUser.RequestCount    += 1;
                        activeUser.SessionExpireMin = sessionExpiresMin;

                        activeUser.Save();
                    }
                    else
                    {
                        CreateModel(userID).Save();
                    }
                }
                else
                {
                    CreateModel(userID).Save();
                }
            }
            catch (Exception ex)
            {
                string error = "";
                CommonMethods.getError(ex, ref error);
                throw new Exception(CommonMethods.ConcatenateErrorIN_DB(DB_Exception.res_23, error, CommonMethods.GetCurrentMethodName()));
            }
        }
        public ActionResult ResendConfirmationToken(string email)
        {
            //using (var db = new ITTContext())
            //{
            //    var tsqlQuery = string.Format("SELECT [ConfirmationToken] FROM [webpages_Membership] WHERE [UserId] IN (SELECT [UserId] FROM [UserProfile] WHERE [Email] LIKE '{0}')", email);
            //    var Token =  db.Database.SqlQuery<string>(tsqlQuery).First();
            //}
            ActiveUser user = unitOfWork.ActiveUserRepository.Get(u => u.Email == email).SingleOrDefault();

            if (user != null)
            {
                var Membership = unitOfWork.Webpages_MembershipRepository.Get(m => m.UserId == user.UserId).Single();
                if (!WebSecurity.IsConfirmed(user.UserName))
                {
                    try
                    {
                        UserMailer.ConfirmResend(new MailResendConfirmationViewModel
                        {
                            EmailAddress = user.Email,
                            DisplayName  = user.firstName + " " + user.lastName,
                            UserName     = user.UserName,
                            Token        = Membership.ConfirmationToken
                        }).Send();
                        return(RedirectToAction("RegisterStepTwo", "Account"));
                    }
                    catch
                    {
                        ModelState.AddModelError("", ControllerError.resendConfirmationEmailError);
                    }
                }
                else
                {
                    return(RedirectToAction("AlreadyConfirmed", "Account"));
                }
            }
            else
            {
                ModelState.AddModelError("", ControllerError.emailWasNotFound);
            }
            return(View());
        }
Example #8
0
        public async Task <IHttpActionResult> PostUser(ActiveUser user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                if (db.Users.Where(u => u.Name == user.Name).Count() > 0)
                {
                    throw new Exception("This user is already exist");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            var plainUser = new User
            {
                //Id = user.Id,
                Age    = user.Age,
                Name   = user.Name,
                Phone  = user.Phone,
                Phrase = user.Phrase
            };

            var image = new Image
            {
                //ImageId = user.Id,
                Name = user.Image
            };

            db.Users.Add(plainUser);
            db.Images.Add(image);

            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = plainUser.UserId }, user));
        }
        public void ThenTheInviteLinksAreIdentical()
        {
            InviteLinkService inviteLinkService = new InviteLinkService();
            ActiveUser        user1             = new ActiveUser
            {
                HouseId  = 3,
                PersonId = 6,
                Created  = DateTime.Now
            };
            ActiveUser user2 = new ActiveUser
            {
                HouseId  = 3,
                PersonId = 7,
                Created  = DateTime.Now
            };

            string inviteCode1 = inviteLinkService.GenerateInviteLinkForHousehold(user1);
            string inviteCode2 = inviteLinkService.GenerateInviteLinkForHousehold(user2);

            Assert.IsTrue(inviteCode1 == inviteCode2);
        }
        private void Add_User_Should_Return_Not_Null_Active_User()
        {
            //Init DBContext
            var options = new DbContextOptionsBuilder <DBContext>()
                          .UseInMemoryDatabase(databaseName: "GetUserDB")
                          .Options;
            var context = new DBContext(options);
            var service = new UserController(context);

            //Save user to database
            context.Add(user);
            context.SaveChanges();

            //Shouldn't return Active user
            ActiveUser activeUser = service.Login(_sessionKeyLogin);

            //Should not be empty.
            Assert.False(emptyActiveUser == activeUser);

            context.Database.EnsureDeleted();
        }
Example #11
0
        //
        // Get Active User from Router
        //
        private List <ActiveUser> getActiveUsers(List <string> command)
        {
            List <ActiveUser> activeUsers = new List <ActiveUser>();

            if (commandRows.Any())
            {
                List <string> rows = new List <string>();
                foreach (string row in commandRows)
                {
                    rows.AddRange(row.Split('|').Where(r => !string.IsNullOrEmpty(r)));
                }
                var result = connection.CallCommandSync(rows.ToArray());
                foreach (var resutlItem in result)
                {
                    ActiveUser au = new ActiveUser();
                    foreach (var word in resutlItem.Words)
                    {
                        if (word.Key.Equals("name"))
                        {
                            au.name = word.Value;
                        }
                        else if (word.Key.Equals("when"))
                        {
                            au.at = word.Value;
                        }
                        else if (word.Key.Equals("via"))
                        {
                            au.via = word.Value;
                        }
                        else if (word.Key.Equals("address"))
                        {
                            au.address = word.Value;
                        }
                    }
                    activeUsers.Add(au);
                }
                commandRows.Clear();
            }
            return(activeUsers);
        }
        public void CreateArticleWithInValidData(string jsonFileName)
        {
            // Arange
            var userPath = Path.GetFullPath(directoryPath + "/Jsons/LoginUserWithValidCredentials.json");
            var user     = ActiveUser.FromJson(File.ReadAllText(userPath));

            var articlePath = Path.GetFullPath(directoryPath + $"/Jsons/{jsonFileName}.json");

            var article = Article.FromJson(File.ReadAllText(articlePath));

            // Act
            driver.Navigate().GoToUrl(loginPage.Url);
            loginPage.LogIn(user);

            homePage.CreateButton.Click();
            createArticlePage.CreateArticleForm(article);


            // Assert
            string errorMessage = "";

            switch (jsonFileName)
            {
            case "ArticleWithInValidContent":
                errorMessage = "The Content field is required.";
                break;

            case "ArticleWithInValidTitle":
                errorMessage = "The Title field is required.";
                break;

            case "ArticleWithEmptyData":
                errorMessage = "The Title field is required.\r\nThe Content field is required.";
                break;

            default:
                break;
            }
            Assert.That(createArticlePage.ErrorMsg.Text.Contains($"{errorMessage}"));
        }
Example #13
0
        private void comboBoxEmployeeID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxEmployeeID.SelectedIndex >= 0)
            {
                ActiveUser activeUser = this.comboBoxEmployeeID.SelectedItem as ActiveUser;
                if (activeUser != null)
                {
                    //JUST SET IN ORDER TO CHANGE PASSWORD
                    ContextAttributes.User = new UserInformation(activeUser.UserID, activeUser.OrganizationalUnitID, activeUser.LocationID, activeUser.LocationName, activeUser.UserName, activeUser.SecurityIdentifier, activeUser.FullyQualifiedUserName, activeUser.IsDatabaseAdmin, new DateTime());


                    string passwordHash = activeUser.PasswordHash;
                    if (passwordHash != "")
                    {
                        passwordHash = SecurePassword.Decrypt(passwordHash);
                    }

                    this.textPassword.Tag = passwordHash;
                }
                this.SetButtonEnabled();
            }
        }
Example #14
0
        public ActionResult MakeOffer(int id, string offerPrice, long?customerId)
        {
            string message = string.Empty, newPrice = offerPrice;
            bool   result = true;

            try
            {
                if ((customerId ?? 0) == 0)
                {
                    customerId = ActiveUser.GetActiveUser().CustomerId;
                }

                if (!customerId.HasValue || customerId.Value == 0)
                {
                    throw new Exception("You are not authorized to submit an offer.");
                }

                ProductService productService = GeneralService.GetProductService();
                Decimal        price          = 0;
                if (Decimal.TryParse(offerPrice, out price))
                {
                    productService.CreateOffer(id, price, customerId.Value);
                    message  = string.Format("Offer for ${0:2} submitted.", offerPrice);
                    newPrice = price.ToString("C");
                }
                else
                {
                    message = string.Format("Offer price ${0} is invalid.", offerPrice);
                }
            }
            catch (Exception ex)
            {
                message = string.Format("Error submitting the offer; {0}", ex.Message);
                result  = false;
            }

            return(Json(new { result = result, message = message, newPrice = newPrice }));
            //return RedirectToAction("Details", new { id = id });
        }
Example #15
0
        public async Task FinalizeRoom(Room room)
        {
            room.SetUsersDomains(typeof(UserDomain.App.Room.FinishedRoom));
            //does this has usage or u can just use lobby idle?

            LastEat(room);

            var roomDataUsersUnOrdered =
                await _masterRepo.GetUsersByIdsAsync(room.RoomActors.Select(_ => _.Id).ToList());

            var roomDataUsers = room.RoomActors.Join(roomDataUsersUnOrdered, ru => ru.Id,
                                                     du => du.Id, (_, du) => du).ToList();

            var scores = CalcScores(room.RoomActors);

            var reportsAndStatus = UpdateUserStates(room, roomDataUsers, scores);

            for (int i = 0; i < roomDataUsers.Count; i++)
            {
                ActiveUser activeUser = room.RoomActors[i] is RoomUser ru
                ? activeUser = ru.ActiveUser
                : null;

                await LevelWorks(roomDataUsers[i], activeUser);
            }

            await _masterRepo.SaveChangesAsync();

            await SendFinalizeResult(room.RoomUsers, roomDataUsers, reportsAndStatus.Item1,
                                     reportsAndStatus.Item2, room.LastEater.TurnId);

            RemoveDisconnectedUsers(room.RoomUsers);

            room.RoomUsers.ForEach(ru => _sessionRepo.DeleteRoomUser(ru));
            _sessionRepo.DeleteRoom(room);

            room.SetUsersDomains(typeof(UserDomain.App.Lobby.Idle));
        }
Example #16
0
        string xyz;//加密后的用户名
        private void button2_Click(object sender, EventArgs e)
        {
            if (File.Exists(@"c:\xinyutian\DataConfig.txt"))
            {
                //存在
                au = new ActiveUser()
                {
                    Login_name = uname.Text.Trim(),
                    Password   = upass.Text.Trim()
                };
                string messageStr = null;

                if (am.Login(au, out messageStr))
                {
                    MessageBox.Show("登录成功");
                    App.user = uname.Text;
                    TextEncrypt(uname.Text.Trim(), psw);
                    string[] strs = { xyz };
                    File.WriteAllLines(@"c:\xinyutian\User.data", strs);
                    //MessageBox.Show("保存成功!");
                    Form3 fm3 = new Form3();
                    fm3.Show();
                    this.Hide();
                }
                else
                {
                    MessageBox.Show(messageStr);
                    uname.Focus();
                }
            }
            else
            {
                //不存在
                MessageBox.Show("数据库未注册,请先注册数据库");
                Form2 fm2 = new Form2();
                fm2.Show();
            }
        }
Example #17
0
        public ActionResult HomeFeed(int?page)
        {
            page = page ?? 1;
            var reader = unitOfWork.ReaderRepository.GetSPDataReader(
                "Feeds",
                new SqlParameter("@pageNum", page),
                new SqlParameter("@U", WebSecurity.CurrentUserId));
            bool         isFinalPage = true;
            IList <Feed> feeds       = new List <Feed>();

            while (reader.Read())
            {
                isFinalPage = false;

                ActiveUser u = new ActiveUser {
                    UserId      = reader.GetInt32(2),
                    firstName   = reader[5] as string,
                    lastName    = reader[6] as string,
                    firstNameEN = reader[7] as string,
                    lastNameEN  = reader [8]  as string,
                    image       = reader[9] as string
                };

                feeds.Add(new Feed
                {
                    feedType = (FeedType)reader.GetInt32(0),
                    elemId   = reader.GetInt32(1),
                    adjId    = reader.GetInt32(2),
                    data     = reader[3] as string,
                    adjUser  = u
                });
            }

            ViewData["finalPage"] = isFinalPage;
            ViewData["pageNum"]   = page;

            return(PartialView(feeds));
        }
Example #18
0
        public static ActiveUser SwitchOrganization(Login login)
        {
            var activeUser = new ActiveUser();
            var token      = JsonConvert.DeserializeObject <ApiResult <UserToken> >(new RestClient(ConfigurationManager.AppSettings["WebAPIURL"]).Execute(
                                                                                        HttpRestClient.RestRequest(Method.POST, "Account/SwitchOrganization")
                                                                                        .AddObject(login)).Content).Results?.FirstOrDefault();

            if (token != null)
            {
                if (!string.IsNullOrEmpty(token.SystemMessage))
                {
                    activeUser.SystemMessage = token.SystemMessage;
                }
                else
                {
                    var tokenRequest = HttpRestClient.RestRequest(Method.GET, "Account/ActiveUser");
                    tokenRequest.AddHeader("Authorization", "bearer " + token.AccessToken);
                    activeUser           = JsonConvert.DeserializeObject <ApiResult <ActiveUser> >(new RestClient(ConfigurationManager.AppSettings["WebAPIURL"]).Execute(tokenRequest).Content).Results?.FirstOrDefault();
                    activeUser.AuthToken = token.AccessToken;
                }
            }
            return(activeUser);
        }
Example #19
0
        public bool Add(ActiveUser au, out string msg)
        {
            msg = null;
            bool isSuccess = false;

            if (au.Login_name.Trim().Length != 0 || au.Password.Trim().Length != 0 || au.Username.Trim().Length != 0) //判断从传递来的username是否为空
            {
                if (!audb.IsEquals(au))                                                                               //传给DALl操作判断数据库中是否有重复值
                {
                    audb.addAu(au);                                                                                   //传给DAL操作增加一个新用户
                    isSuccess = true;
                }
                else
                {
                    msg = "有相同的值";
                }
            }
            else
            {
                msg = "不能为空";
            }
            return(isSuccess);//返回界面层是否添加成功
        }
Example #20
0
        public bool LogOut(string username, string ipaddress, string hostname)
        {
            ActiveUser au      = new ActiveUser();
            bool       _status = false;

            try
            {
                au = (from a in DB.ActiveUser
                      where a.UserName == username && a.Login_Time != null && a.Logout_Time == null && a.IP_Address == ipaddress && a.Host_Name == hostname
                      select a).FirstOrDefault <ActiveUser>();
                if (au != null)
                {
                    try
                    {
                        au.Logout_Time = DateTime.Now;
                        DB.SubmitChanges();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        ex.LogException();
                        DB.ActiveUser.Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, au);
                    }
                }
            }

            catch (System.Data.Linq.ChangeConflictException)
            {
                DB.ChangeConflicts.ResolveAll(System.Data.Linq.RefreshMode.KeepChanges);
            }
            catch (Exception ex)
            {
                ex.LogException();
                DB.ActiveUser.Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, au);
            }
            return(_status);
        }
Example #21
0
        public AddToDoResponse AddToDoItem([FromBody] AddToDoTaskRequest toDoTaskRequest)
        {
            var response = new AddToDoResponse();

            try
            {
                if (_userService.AuthenticateSession(Request.Headers["Authorization"].ToString()) == false)
                {
                    response.AddError("The authorization credentails were invalid", ErrorCode.SESSION_INVALID);
                    return(response);
                }

                ActiveUser user = _userService.GetUserInformationFromAuthHeader(Request.Headers["Authorization"].ToString());
                if (user.HouseId == 0)
                {
                    response.AddError("You must belong to a household to add To Do Tasks", ErrorCode.USER_NOT_IN_HOUSEHOLD);
                    return(response);
                }
                response.Id = _toDoRepository.AddToDoTask(toDoTaskRequest, user.HouseId);

                response.Notifications = new List <string>
                {
                    $"The task '{toDoTaskRequest.Title}' has been added"
                };
            }
            catch (ErrorCodeException exception)
            {
                response.AddError($"An unexpected exception occured: {exception}", toDoTaskRequest, exception.Code);
            }
            catch (Exception exception)
            {
                response.AddError($"An unexpected exception occured: {exception}", toDoTaskRequest);
            }

            return(response);
        }
Example #22
0
        public async Task RequestRandomRoom(int betChoice, int capacityChoice,
                                            ActiveUser activeUser)
        {
            if (!betChoice.IsInRange(Room.Bets.Length) ||
                !capacityChoice.IsInRange(Room.Capacities.Length))
            {
                throw new BadUserInputException();
            }

            var dUser = await _masterRepo.GetUserByIdAsyc(activeUser.Id);

            if (dUser.Money < Room.Bets[betChoice])
            {
                throw new BadUserInputException();
            }

            var room     = TakeOrCreateAppropriateRoom(betChoice, capacityChoice);
            var roomUser = CreateRoomUser(activeUser, room);

            room.RoomUsers.Add(roomUser);
            room.RoomActors.Add(roomUser);

            RemoveDisconnectedUsers(room);

            if (room.IsFull)
            {
                _serverLoop.CancelPendingRoomTimeout(room);
                await PrepareRoom(room);
            }
            else
            {
                activeUser.Domain = typeof(UserDomain.App.Lobby.Pending);
                _serverLoop.SetupPendingRoomTimeoutIfNotExist(room);
                _sessionRepo.KeepPendingRoom(room);
            }
        }
Example #23
0
        /// <summary>
        /// check current level against xp to level up and send to client
        /// functions that takes data user as param doesn't save changes
        /// </summary>
        private async Task LevelWorks(User roomDataUser, ActiveUser activeUser)
        {
            var calcedLevel = Room.GetLevelFromXp(roomDataUser.XP);

            if (calcedLevel > roomDataUser.Level)
            {
                var increasedLevels  = calcedLevel - roomDataUser.Level;
                var totalMoneyReward = 0;
                for (int j = 0; j < increasedLevels; j++)
                {
                    totalMoneyReward += 100;
                    //todo give level up rewards (money equation), add to test
                    //todo test this function logic
                }

                roomDataUser.Level  = calcedLevel;
                roomDataUser.Money += totalMoneyReward;

                if (activeUser != null)
                {
                    await _masterHub.SendOrderedAsync(activeUser, "LevelUp", calcedLevel, totalMoneyReward);
                }
            }
        } //separate this to be called on every XP change
Example #24
0
        public string GenerateInviteLinkForHousehold(ActiveUser user)
        {
            if (user.HouseId < 0)
            {
                throw new ErrorCodeException("Cannot create an invite link for a user who does not belong to a Household", ErrorCode.USER_NOT_IN_HOUSEHOLD);
            }

            string existingKey = _cachedInviteLinks.FirstOrDefault(inviteLink => inviteLink.Value.Id == user.HouseId).Key;

            if (existingKey != null)
            {
                bool valid = CheckExpiry(existingKey);
                if (valid)
                {
                    return(existingKey);
                }
            }

            string        possibleCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            Random        randomGenerator    = new Random();
            StringBuilder stringBuilder      = new StringBuilder();

            for (int inviteIndex = 0; inviteIndex < 6; ++inviteIndex)
            {
                stringBuilder.Append(possibleCharacters[randomGenerator.Next(possibleCharacters.Length)]);
            }

            string inviteCode = stringBuilder.ToString();

            _cachedInviteLinks.Add(inviteCode, new HouseInvite
            {
                Id      = user.HouseId,
                Created = DateTime.Now
            });
            return(inviteCode);
        }
Example #25
0
        public GetShoppingResponse GetShoppingItems(int?page, int?resultsPerPage)
        {
            var response = new GetShoppingResponse();

            try
            {
                if (_userService.AuthenticateSession(Request.Headers["Authorization"].ToString()) == false)
                {
                    response.AddError("The authorization credentails were invalid", ErrorCode.SESSION_INVALID);
                    return(response);
                }

                ActiveUser user = _userService.GetUserInformationFromAuthHeader(Request.Headers["Authorization"].ToString());
                if (user.HouseId == 0)
                {
                    response.AddError("You must belong to a household to get shopping items", ErrorCode.USER_NOT_IN_HOUSEHOLD);
                    return(response);
                }
                Pagination pagination = new Pagination
                {
                    Page           = page ?? 0,
                    ResultsPerPage = resultsPerPage ?? int.MaxValue
                };
                response.ShoppingList = _shoppingRepository.GetAllItems(pagination, user.HouseId);
            }
            catch (ErrorCodeException exception)
            {
                response.AddError($"An unexpected exception occured: {exception}", exception.Code);
            }
            catch (Exception exception)
            {
                response.AddError($"An unexpected exception occured: {exception}");
            }

            return(response);
        }
Example #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            au = new ActiveUser()
            {
                Login_name = lname.Text,
                Username   = uname.Text,
                Password   = upass.Text
            };
            string messageStr = null;

            if (am.Add(au, out messageStr))
            {
                MessageBox.Show("添加操作员成功");
                //Form2 fm2 = new Form2();
                //fm2.Show();
                //this.Hide();
                this.Close();
            }
            else
            {
                MessageBox.Show(messageStr);
                uname.Focus();
            }
        }
Example #27
0
        } //trivial to test, best in integration

        // public async Task MakeMoneyAimClaimable(string userId)
        // {
        //     var user = await _masterRepo.GetUserByIdAsyc(userId);
        //
        //     // user.IsMoneyAidClaimable = true;
        //     // user.LastMoneyAimRequestTime = null;
        //
        //     //we don't notify the client for 2 reasons:
        //     //he could be inactive and when he request/start he know the remaining time
        //     //when he checks for claimable flag he can claim
        //     await _masterRepo.SaveChangesAsync();
        // } //issue changes, no test

        public async Task ClaimMoneyAim(ActiveUser activeUser)
        {
            var user = await _masterRepo.GetUserByIdAsyc(activeUser.Id);

            if (user.LastMoneyAimRequestTime == null)
            {
                throw new BadUserInputException(
                          "the user was trying to claim while he didn't request");
            }
            if (user.LastMoneyAimRequestTime.SecondsPassedSince() < ConstData.MoneyAimTime)
            {
                throw new BadUserInputException(
                          "the user was trying to claim while the time is not done");
            }

            user.LastMoneyAimRequestTime = null;
            user.Money += Room.MinBet;

            await _masterRepo.SaveChangesAsync();

            //I didn't send the user to let the client sync the state and figure out because the
            //situation is customized so not returning error in itself means the client can make the receive money
            //animation and ui update
        } //don't test
Example #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));
            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);
            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = appSettingsSection["JwtIssuer"],
                    ValidAudience    = appSettingsSection["JwtIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettingsSection["Secret"])),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                };
                cfg.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                            (path.StartsWithSegments("/chatHub/negotiate")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return(Task.CompletedTask);
                    }
                };
            });


            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient <ClaimsPrincipal>(
                x =>
            {
                var currentContext = x.GetService <IHttpContextAccessor>();
                if (currentContext.HttpContext != null)
                {
                    var claimsPrincipal = currentContext.HttpContext.User;
                    return(claimsPrincipal);
                }
                else
                {
                    return(null);
                }
            }
                );
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "JwtAuthentication",
                    Version     = "1",
                    Description = "Jwt Authentication"
                });



                c.AddSecurityDefinition("Bearer",
                                        new Microsoft.OpenApi.Models.OpenApiSecurityScheme
                {
                    In          = ParameterLocation.Header,
                    Description = "Please enter into field the word 'Bearer' following by space and JWT",
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.ApiKey
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header,
                        },
                        new List <string>()
                    }
                });
            });
            //Extract the Logged in person information from the token
            services.AddScoped <ActiveUser>(
                x =>
            {
                var currentContext = x.GetService <IHttpContextAccessor>();

                if (currentContext != null && currentContext.HttpContext != null && currentContext.HttpContext.User != null)
                {
                    var claimsPrincipal = currentContext.HttpContext.User;
                    ActiveUser ai       = new ActiveUser();
                    ai.UserId           = Convert.ToInt32(claimsPrincipal.Claims.Where(e => e.Type == "user_id").Select(e => e.Value).FirstOrDefault());
                    ai.UserName         = claimsPrincipal.Claims.Where(e => e.Type == ClaimTypes.Name).Select(e => e.Value).FirstOrDefault();
                    return(ai);
                }
                else
                {
                    return(null);
                }
            }
                );

            services.AddHttpContextAccessor();
            services.AddDbContext <ApplicationDbContext>();
            services.AddScoped <IUserService, UserService>();
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                                         builder.SetIsOriginAllowed(_ => true)
                                         .AllowAnyMethod()
                                         .AllowAnyHeader()
                                         .AllowCredentials());
            });
        }
Example #29
0
        public static void PurchaseOrderCreationProcessForNAV(ActiveUser activeUser, List <long> jobIdList, string navAPIUrl, string navAPIUserName, string navAPIPassword, bool electronicInvoice)
        {
            bool                     isElectronicInvoice                = false;
            bool                     isManualInvoice                    = false;
            NavPurchaseOrder         manualPurchaseOrder                = null;
            NavPurchaseOrder         electronicPurchaseOrder            = null;
            List <PurchaseOrderItem> manualPurchaseOrderItemRequest     = null;
            List <PurchaseOrderItem> electronicPurchaseOrderItemRequest = null;
            List <PurchaseOrderItem> purchaseOrderItemRequest           = _commands.GetPurchaseOrderItemCreationData(activeUser, jobIdList, Entities.EntitiesAlias.PurchaseOrderItem);

            if (purchaseOrderItemRequest == null || (purchaseOrderItemRequest != null && purchaseOrderItemRequest.Count == 0))
            {
                isManualInvoice     = true;
                isElectronicInvoice = false;
            }
            else if (purchaseOrderItemRequest != null && purchaseOrderItemRequest.Count > 0)
            {
                isElectronicInvoice                = purchaseOrderItemRequest.Where(x => x.Electronic_Invoice).Any() ? true : false;
                isManualInvoice                    = purchaseOrderItemRequest.Where(x => !x.Electronic_Invoice).Any() ? true : false;
                manualPurchaseOrderItemRequest     = isManualInvoice ? purchaseOrderItemRequest.Where(x => !x.Electronic_Invoice).ToList() : null;
                electronicPurchaseOrderItemRequest = isElectronicInvoice ? purchaseOrderItemRequest.Where(x => x.Electronic_Invoice).ToList() : null;
            }

            if (jobIdList != null && jobIdList.Count > 0)
            {
                foreach (var currentJob in jobIdList)
                {
                    Entities.Job.Job jobData = _jobCommands.GetJobByProgram(activeUser, currentJob, 0);
                    if ((!jobData.JobElectronicInvoice ||
                         (purchaseOrderItemRequest != null && purchaseOrderItemRequest.Count > 0 && !purchaseOrderItemRequest.Where(x => x.Electronic_Invoice).Any())) &&
                        !string.IsNullOrEmpty(jobData.JobElectronicInvoicePONumber))
                    {
                        bool isDeleted = false;
                        DeletePurchaseOrderForNAV(jobData.JobElectronicInvoicePONumber, jobData.Id, true, navAPIUrl, navAPIUserName, navAPIPassword, out isDeleted);
                        jobData.JobElectronicInvoicePONumber = isDeleted ? string.Empty : jobData.JobElectronicInvoicePONumber;
                    }

                    if (!string.IsNullOrEmpty(jobData.JobPONumber) && ((purchaseOrderItemRequest == null || (purchaseOrderItemRequest != null && purchaseOrderItemRequest.Count == 0)) || (purchaseOrderItemRequest != null && purchaseOrderItemRequest.Count > 0 && !purchaseOrderItemRequest.Where(x => !x.Electronic_Invoice).Any())))
                    {
                        bool isDeleted = false;
                        DeletePurchaseOrderForNAV(jobData.JobPONumber, jobData.Id, false, navAPIUrl, navAPIUserName, navAPIPassword, out isDeleted);
                        jobData.JobPONumber = isDeleted ? string.Empty : jobData.JobPONumber;
                    }

                    if (!jobData.JobElectronicInvoice || (jobData.JobElectronicInvoice && (purchaseOrderItemRequest == null || (purchaseOrderItemRequest != null && purchaseOrderItemRequest.Count == 0))) || (jobData.JobElectronicInvoice && purchaseOrderItemRequest != null && purchaseOrderItemRequest.Count > 0 && !purchaseOrderItemRequest.Where(x => x.Electronic_Invoice).Any()))
                    {
                        if (jobData.JobElectronicInvoice)
                        {
                            if (string.IsNullOrEmpty(jobData.JobElectronicInvoicePONumber))
                            {
                                manualPurchaseOrder = GeneratePurchaseOrderForNAV(activeUser, jobIdList, navAPIUrl, navAPIUserName, navAPIPassword,
                                                                                  jobData.JobElectronicInvoice, purchaseOrderItemRequest);
                            }
                            else
                            {
                                manualPurchaseOrder = UpdatePurchaseOrderForNAV(activeUser, jobIdList,
                                                                                string.IsNullOrEmpty(jobData.JobElectronicInvoicePONumber) ? jobData.JobPONumber : jobData.JobElectronicInvoicePONumber,
                                                                                navAPIUrl, navAPIUserName, navAPIPassword, jobData.JobElectronicInvoice, purchaseOrderItemRequest);
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(jobData.JobPONumber))
                            {
                                manualPurchaseOrder = GeneratePurchaseOrderForNAV(activeUser, jobIdList, navAPIUrl, navAPIUserName, navAPIPassword, jobData.JobElectronicInvoice, purchaseOrderItemRequest);
                            }
                            else
                            {
                                manualPurchaseOrder = UpdatePurchaseOrderForNAV(activeUser, jobIdList,
                                                                                string.IsNullOrEmpty(jobData.JobPONumber) ? jobData.JobElectronicInvoicePONumber : jobData.JobPONumber, navAPIUrl, navAPIUserName, navAPIPassword,
                                                                                jobData.JobElectronicInvoice, purchaseOrderItemRequest);
                            }
                        }
                    }
                    else
                    {
                        if (isManualInvoice)
                        {
                            if (string.IsNullOrEmpty(jobData.JobPONumber))
                            {
                                manualPurchaseOrder = GeneratePurchaseOrderForNAV(activeUser, jobIdList, navAPIUrl, navAPIUserName, navAPIPassword,
                                                                                  false, manualPurchaseOrderItemRequest);
                            }
                            else
                            {
                                manualPurchaseOrder = UpdatePurchaseOrderForNAV(activeUser, jobIdList, string.IsNullOrEmpty(jobData.JobPONumber) ? jobData.JobElectronicInvoicePONumber : jobData.JobPONumber, navAPIUrl, navAPIUserName, navAPIPassword,
                                                                                false, manualPurchaseOrderItemRequest);
                            }
                        }

                        if (isElectronicInvoice)
                        {
                            if (string.IsNullOrEmpty(jobData.JobElectronicInvoicePONumber))
                            {
                                electronicPurchaseOrder = GeneratePurchaseOrderForNAV(activeUser, jobIdList, navAPIUrl, navAPIUserName, navAPIPassword,
                                                                                      true, electronicPurchaseOrderItemRequest);
                            }
                            else
                            {
                                electronicPurchaseOrder = UpdatePurchaseOrderForNAV(activeUser, jobIdList, !string.IsNullOrEmpty(jobData.JobElectronicInvoicePONumber) ? jobData.JobElectronicInvoicePONumber : jobData.JobPONumber, navAPIUrl, navAPIUserName, navAPIPassword,
                                                                                    true, electronicPurchaseOrderItemRequest);
                            }
                        }
                    }
                }
            }
        }
Example #30
0
        private static void UpdateLineItemInformationForPurchaseOrder(ActiveUser activeUser, List <long> jobIdList, string navAPIUrl, string navAPIUserName, string navAPIPassword, string dimensionCode, string divisionCode, string poNumber, out string proFlag, bool isElectronicInvoice, List <PurchaseOrderItem> purchaseOrderItemRequest)
        {
            bool   allLineItemsUpdated = true;
            string deleteProFlag       = null;
            bool   allLineItemsDeleted = true;
            List <NavPurchaseOrderItemRequest> navPurchaseOrderItemRequest = null;

            if (purchaseOrderItemRequest != null && purchaseOrderItemRequest.Count > 0)
            {
                navPurchaseOrderItemRequest = new List <NavPurchaseOrderItemRequest>();
                purchaseOrderItemRequest.ToList().ForEach(x => navPurchaseOrderItemRequest.Add(new NavPurchaseOrderItemRequest()
                {
                    No                        = x.No,
                    M4PLItemId                = x.M4PLItemId,
                    Document_No               = x.Document_No,
                    M4PL_Job_ID               = x.M4PL_Job_ID,
                    Quantity                  = x.Quantity,
                    Qty_to_Receive            = x.Qty_to_Receive,
                    Qty_to_Invoice            = x.Qty_to_Invoice,
                    Promised_Receipt_Date     = x.Promised_Receipt_Date,
                    Expected_Receipt_Date     = x.Expected_Receipt_Date,
                    Order_Date                = x.Order_Date,
                    Line_No                   = x.Line_No,
                    Type                      = x.Type,
                    FilteredTypeField         = x.FilteredTypeField,
                    Shortcut_Dimension_1_Code = x.Shortcut_Dimension_1_Code,
                    Shortcut_Dimension_2_Code = x.Shortcut_Dimension_2_Code
                }));
            }

            List <JobOrderItemMapping> jobOrderItemMapping = _commands.GetJobOrderItemMapping(jobIdList, Entities.EntitiesAlias.PurchaseOrder, isElectronicInvoice);
            bool isRecordUpdated = true;
            bool isRecordDeleted = true;

            if (jobOrderItemMapping != null && jobOrderItemMapping.Count > 0)
            {
                DeleteLineItemInformationForPurchaseOrder(activeUser, jobIdList, navAPIUrl, navAPIUserName, navAPIPassword, isElectronicInvoice, allLineItemsUpdated, navPurchaseOrderItemRequest, jobOrderItemMapping, poNumber, ref deleteProFlag, ref allLineItemsDeleted, ref isRecordDeleted);
            }

            NavPurchaseOrderItem navPurchaseOrderItemResponse = null;

            if (navPurchaseOrderItemRequest != null && navPurchaseOrderItemRequest.Count > 0)
            {
                foreach (var navPurchaseOrderItemRequestItem in navPurchaseOrderItemRequest)
                {
                    navPurchaseOrderItemRequestItem.Shortcut_Dimension_2_Code = dimensionCode;
                    navPurchaseOrderItemRequestItem.Shortcut_Dimension_1_Code = divisionCode;
                    if (jobOrderItemMapping != null && jobOrderItemMapping.Count > 0 && jobOrderItemMapping.Where(x => x.EntityName == Entities.EntitiesAlias.PurchaseOrderItem.ToString() && x.LineNumber == navPurchaseOrderItemRequestItem.Line_No && x.M4PLItemId == navPurchaseOrderItemRequestItem.M4PLItemId).Any())
                    {
                        navPurchaseOrderItemResponse = UpdatePurchaseOrderItemForNAV(navPurchaseOrderItemRequestItem, navAPIUrl, navAPIUserName, navAPIPassword, activeUser, jobIdList, out isRecordUpdated);
                    }
                    else
                    {
                        navPurchaseOrderItemResponse = GeneratePurchaseOrderItemForNAV(navPurchaseOrderItemRequestItem, navAPIUrl, navAPIUserName, navAPIPassword, activeUser, jobIdList, out isRecordUpdated);
                    }

                    allLineItemsUpdated          = !allLineItemsUpdated ? allLineItemsUpdated : isRecordUpdated;
                    isRecordUpdated              = true;
                    navPurchaseOrderItemResponse = null;
                }
            }

            proFlag = allLineItemsUpdated ? deleteProFlag : Entities.ProFlag.I.ToString();
            _commands.UpdateJobProFlag(activeUser, proFlag, jobIdList, Entities.EntitiesAlias.PurchaseOrder);
        }
Example #31
0
        void ISoundLocalizationEvents.ActiveSoundUser(ActiveUser userAct, double LeftValue, double RightValue)
        {
            currentlyActiveSpeaker = userAct;
            Debug("Floor: " + currentlyActiveSpeaker);
            if (performingUtterance != null && performingUtterance.IsQuestion && !backchanneledCurrentQuestion && backchannelingCategory != "")
            {
                if (userAct != ActiveUser.None) backchannellingCurrentQuestion = true;
                else if (userAct == ActiveUser.None && backchannellingCurrentQuestion)
                {
                    string[] s_backchannelingCategory = backchannelingCategory.Split(':');
                    string category = s_backchannelingCategory[0];
                    string subcategory = s_backchannelingCategory.Length > 1 ? s_backchannelingCategory[1] : "-";
                    Utterance backChannelUtterance = null;
                    if (UseCompositeLibrary)
                    {
                        backChannelUtterance = UtteranceLibrary.GetCompositeUtterance(utteranceLibraries.Values.ToList(), category, subcategory);
                    }
                    else
                    {
                        if (utteranceLibraries.ContainsKey(SelectedLibrary)) backChannelUtterance = utteranceLibraries[SelectedLibrary].GetUtterance(category, subcategory);
                    }
                    if (backChannelUtterance != null)
                    {
                        backchanneledCurrentQuestion = true;

                        lock (utterancesQueue)
                        {
                            Queue<Utterance> q = new Queue<Utterance>(utterancesQueue);
                            utterancesQueue.Clear();
                            //utterancesQueue.Enqueue(backChannelUtterance);
                            PerformUtterance("", backChannelUtterance);
                            foreach (Utterance u in q)
                            {
                                utterancesQueue.Enqueue(u);
                                Utterances.HistoryManager.HistoryManagerFactory.GetHistoryManager().AddToHistory(u.ThalamusId, u);
                            }
                        }
                        waitingForQuestionAnswer = false;
                    }
                }
            }
        }