public void SaveANewMemberWithNullUser()
 {
     _story.WithScenario("Save a new Member with  empty properties' value")
         .Given("the new member with nothing", () => { _Uobject = new UserObject(); })
         .When("I save this member")
         .Then("I Get an Excepton from ", () => typeof(ArgumentNullException).ShouldBeThrownBy(() => _membershipApi.Save(_Uobject, _password, _passwordAnswer)));
 }
        public void ChangeUserPasswordObeyPasswordRule()
        {
            _story = new Story("Change Memebers' password By IMembershipApi");

            _story.AsA("User")
              .IWant("to be able to change the password")
              .SoThat("I can use new password to login");

            _story.WithScenario("Change the password with a correct GUID")
                .Given("Create a new User with old password, but the new password doesn't follow the password rule", () =>
                {
                    _Uobject = _utils.CreateUserObject("Eunge Liu", true);

                    _oldpassword = "******";

                    _newpassword = "******";

                    _membershipApi.Save(_Uobject, _oldpassword, "123Hello");

                    createdObjectIds.Add(_Uobject.UserId);

                })
                .When("I change the password ", () =>
                {

                })
                .Then("I can get Error Message from ChangePassword method",
                        () =>
                        {
                            typeof(ValidationException).ShouldBeThrownBy(() => _membershipApi.ChangePassword(_Uobject.UserId, _oldpassword, _newpassword));
                        });

            this.CleanUp();
        }
Exemplo n.º 3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["User"] == null)
        {
            Session["ErrorMessage"] = "You need to be logged in first";
            Response.Redirect("~/Login.aspx");
        }
        user = (UserObject)Session["User"];

        if (user.character == null)
        {
            Session["ErrorMessage"] = "You need to have a card character before battling.";
            Response.Redirect("~/CreateAChar.aspx");
        }
        self = (CharacterObject)user.character;

        if (Session["Opponent"] == null)
        {
            Response.Redirect("~/Default.aspx");
        }
        opponent = (CharacterObject)Session["Opponent"];

        litAtk.Text = "<span>" + self.Attack + "</span>";
        imgSelf.ImageUrl = self.ImageUrl;

        litHp.Text = "<span>?/?</span>";
        imgOther.ImageUrl = opponent.ImageUrl;
    }
        public UserObject CreateUserObject(string displayName, bool IsApproved)
        {
            IPlatformConfiguration platformConfiguration = SpringContext.Current.GetObject<IPlatformConfiguration>();

            UserObject userObject = new UserObject
            {
                OrganizationId = platformConfiguration.Organization.OrganizationId,
                Comment = "IT specialist",
                DisplayName = displayName,
                Email = "*****@*****.**",
                IsApproved = IsApproved,
                MobilePin = "137641855XX",
                UserName = displayName
            };

            userObject["Birthday"] = new DateTime(1982, 2, 7);
            userObject["Sex"] = "Male";
            userObject["IdentityNo"] = "51010419820207XXXX";
            userObject["EmployeeNo"] = "200708200002";
            userObject["Department"] = "Simulation";
            userObject["Position"] = "Team Lead";
            userObject["PhoneNo"] = "021-647660XX";
            userObject["City"] = "ShangHai";
            userObject["Address"] = "MeiLong 2nd Cun, MingHang District";
            userObject["ZipCode"] = "210000";

            return userObject;
        }
Exemplo n.º 5
0
    protected void btnSure_Click(object sender, EventArgs e)
    {
        UserObject dep = new UserObject();
        WebFormHelper.GetDataFromForm(this, dep);
        dep.BeginIp = this.txtBeginIp1.Text.Trim() + "." + this.txtBeginIp2.Text.Trim() + "." + this.txtBeginIp3.Text.Trim() + "." + this.txtBeginIp4.Text.Trim();
        dep.EndIp = this.txtEndIp1.Text.Trim() + "." + this.txtEndIp2.Text.Trim() + "." + this.txtEndIp3.Text.Trim() + "." + this.txtEndIp4.Text.Trim();
        if (dep.Id < 0)
        {
            dep.Password = SecurityFactory.GetSecurity().Encrypt(ConfigurationManager.AppSettings["DefaultPassword"].ToString());

            if (SimpleOrmOperator.Create(dep))
            {
                WebTools.Alert("添加成功!");
            }
            else
            {
                WebTools.Alert("添加失败!");

            }
        }
        else
        {
            if (SimpleOrmOperator.Update(dep))
            {
                WebTools.Alert("修改成功!");
            }
            else
            {
                WebTools.Alert("修改失败!");

            }
        }
    }
 public void SaveANewMemberWithValuesAndEmptyPassword()
 {
     _story.WithScenario("Save a new Member with value")
         .Given("the new member with nothing", () => { _Uobject = CreateUserObject(); })
         .And("Give the Password and PasswordAnser", () => { _password = ""; _passwordAnswer = ""; })
         .When("I save this member")
         .Then("I Get an new User ", () => typeof(ArgumentNullException).ShouldBeThrownBy(() => _membershipApi.Save(_Uobject, _password, _passwordAnswer)));
 }
 public void SaveANewMemberWithValues()
 {
     _story.WithScenario("Save a new Member with value")
         .Given("the new member with nothing", () => { _Uobject = CreateUserObject(); })
         .And("Give the Password and PasswordAnser", () => { _password = "******"; _passwordAnswer = "123Hello"; })
         .When("I save this member", () => _membershipApi.Save(_Uobject, _password, _passwordAnswer))
         .Then("I Get an new User ", () => _Uobject.ApplicationId.ShouldNotBeNull());
 }
Exemplo n.º 8
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (ValidData())
        {
            UserObject user = new UserObject();
            user.Name.Value = tbName.Text;
            user.Password.Value = tbPassword.Text;
            user.LoginName.Value = tbLoginName.Text;
            user.IsActive.Value = cbActive.Checked;
            /*if (ddlClients.SelectedIndex > 0)
            {
                user.ClientId.Value = ddlClients.SelectedValue;
            }*/
            user.Answer.Value = tbAnswer.Text;
            user.SecretQuestionId.Value = SecretQuestions1.SecretQuestionId;
            user.ResetPassword.Value = cbResetPassword.Checked;
            /*if (ddlHospitals.SelectedIndex > 0)
            {
                user.HospitalId.Value = ddlHospitals.SelectedValue;
            }*/
            user.SendSMS.Value = cbSms.Checked;
            user.Mobile.Value = tbCellNumber.Text;
            if (ddlCarriers.SelectedValue != "0")
            {
                user.CarrierId.Value = ddlCarriers.SelectedValue;
            }

            user.Save(loggedInUserId);
            if (user.IsLoaded)
            {
                UserRoleObject userRole = new UserRoleObject();
                userRole.UserId.Value = user.UserId.Value;
                userRole.RoleId.Value = ddlRoles.SelectedValue;
                userRole.Save(loggedInUserId);
                UsersTableAdapters.tUsersTableAdapter userTA = new UsersTableAdapters.tUsersTableAdapter();
                userTA.AssignClientsToUser(int.Parse(user.UserId.Value.ToString()),loggedInUserId);
                /*
                UsersTableAdapters.tUsersTableAdapter userTA = new UsersTableAdapters.tUsersTableAdapter();
                if (user.HospitalId.Value != null)
                {
                    Nullable<int> userId = int.Parse(user.UserId.Value.ToString());
                    Nullable<int> hospitalId = int.Parse(user.HospitalId.Value.ToString());
                    userTA.AssignHospitalToUser(userId, hospitalId, false, loggedInUserId);
                }
                else
                {
                    userTA.AssignHospitalToUser((Nullable<int>)user.UserId.Value, null, false, loggedInUserId);
                }
                */
                Response.Redirect("~/Admin/AddUser.aspx?userId=" + user.UserId.Value);
            }

            SetInfoMessage("User saved successfully");
        }
    }
        public void Setup()
        {
            string serviceUri1 = @"/OrganizationService.svc/json/SaveOrganizationType";
            string serviceUriorganization = @"/OrganizationService.svc/json/SaveOrganization";

            organizationTypeObject = new OrganizationTypeObject() { Name = "Manager" + Guid.NewGuid().ToString().Substring(0, 5), Domain = "Department", Description = "department-desc", LastUpdatedDate = System.DateTime.Now };
            string organizationTypeId = TestServicesHelper.GetResponse<HttpWebRequest>(serviceUri1, userName, password, TestServicesHelper.PostDataByJsonWithContent, TestServicesHelper.GenerateJsonByType(organizationTypeObject), null).Replace("\"", "");

            organizationTypeObject.OrganizationTypeId = new Guid(organizationTypeId);
            organizationObject = new OrganizationObject()
            {
                OrganizationCode = "sh021" + Guid.NewGuid().ToString().Substring(0, 5),
                OrganizationName = "sh-department" + Guid.NewGuid().ToString().Substring(0, 5),
                OrganizationTypeId = organizationTypeObject.OrganizationTypeId,
                Status = OrganizationStatus.Enabled,
                Description = "sh-desc",
                CreatedDate = System.DateTime.Now,
                LastUpdatedDate = System.DateTime.Now

            };

            string organizationId = TestServicesHelper.GetResponse<HttpWebRequest>(serviceUriorganization, userName, password, TestServicesHelper.PostDataByJsonWithContent, TestServicesHelper.GenerateJsonByType(organizationObject), null).Replace("\"", "");
            organizationObject.OrganizationId = new Guid(organizationId);

            common = new UserObject
            {
                UserName = "******" + Guid.NewGuid().ToString().Substring(0, 5),
                DisplayName = "CommonUser" + Guid.NewGuid().ToString().Substring(0, 5),
                LastActivityDate = DateTime.Now,
                LastLockoutDate = DateTime.Now,
                LastLoginDate = DateTime.Now,
                LastPasswordChangedDate = DateTime.Now,
                CreationDate = System.DateTime.Now,
                OrganizationId = organizationObject.OrganizationId,
                LastUpdatedDate = DateTime.Now,
                PasswordQuestion = pwdAns
            };
            string serviceUri = string.Format("/MembershipService.svc/json/Save");

            string content = TestServicesHelper.GenerateJsonByType(common);
            IDictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("password", pwd);
            parameters.Add("passwordAnswer", pwdAns);

            string id = TestServicesHelper.GetResponse<HttpWebRequest>(serviceUri, userName, password, TestServicesHelper.PostDataByJsonWithContent, content, parameters).Replace("\"", "");
            common.UserId = new Guid(id);

            super = new RoleObject { RoleName = "super", Domain = "Department", Description = "super role" };
            string serviceUriRole = @"/RoleService.svc/json/Save";

            string contentRole = TestServicesHelper.GenerateJsonByType(super);
            string idRole = TestServicesHelper.GetResponse<HttpWebRequest>(serviceUriRole, userName, password, TestServicesHelper.PostDataByJsonWithContent, contentRole, null).Replace("\"", "");
            super.RoleId = new Guid(idRole);
        }
Exemplo n.º 10
0
 protected void btnResetPassword2_Click(object sender, EventArgs e)
 {
     UserObject user = new UserObject();
     user.LoginName.Value = tbLoginName.Text;
     user.Load();
     if (user.IsLoaded && tbPassword.Text.Equals(tbConfirmPassword.Text))
     {
         user.Password.Value = tbPassword.Text;
         user.Save();
         Response.Redirect("~/SharedPages/Login.aspx");
     }
 }
Exemplo n.º 11
0
        public void Initialized()
        {
            //role
            GroupRoleObject groupRole = null;

            groupRole = new GroupRoleObject();
            groupRole.Id = "7E946ED1-69E6-4B45-8273-FB7AC7367F50";
            groupRole.GroupName = "Manager";
            session.Store(groupRole);

            groupRole = new GroupRoleObject();
            groupRole.Id = "79C6B725-F787-4FDF-B820-42A21174449D";
            groupRole.GroupName = "Owner";
            session.Store(groupRole);

            groupRole = new GroupRoleObject();
            groupRole.Id = "9A17E51B-7EAB-4E80-B3E4-6C3D44DCE3EB";
            groupRole.GroupName = "Member";
            session.Store(groupRole);

            //user
            UserObject userObject = null;

            userObject = new UserObject();
            userObject.Id = "D035A3B8-961D-4DA0-827A-D58E8FCE3832";
            userObject.FullName = "Duong Than Dan";
            userObject.UserName = "******";
            userObject.Password = "******";
            userObject.Email = "*****@*****.**";
            session.Store(userObject);

            userObject = new UserObject();
            userObject.Id = "F4D45AD1-D581-425C-A058-799AFA51FE01";
            userObject.FullName = "Bui Ngoc Huy";
            userObject.UserName = "******";
            userObject.Password = "******";
            userObject.Email = "*****@*****.**";
            session.Store(userObject);

            ////group
            //GroupObject groupObject = null;

            //groupObject = new GroupObject();
            //groupObject.Id = "";
            //groupObject.GroupName = "group 1";
            //groupObject.Description = "this is group 1";
            //groupObject.IsPublic = true;
            //groupObject.CreateDate = DateTime.Now;
            //session.Store(groupObject);

            session.SaveChanges();
        }
    public void reset()
    {
        _firstPreviousUserObject = new UserObject();
        _secondPreviousUserObject = new UserObject();
        _nextUserObject = new UserObject();

        _isFirstPreviousUserJiaoDiZhu = false;
        _isFirstPreviousUserFirstJiaoDiZhu = false;

        _isSecondPreviousUserJiaoDiZhu = false;
        _isSecondPreviousUserFirstJiaoDiZhu = false;

        _isNextUserFirstJiaoDiZhu = false;
    }
Exemplo n.º 13
0
        public Boolean CreateUser(String name, String contact, String role, String username, String password, String confirm_password)
        {
            //set the properties of the new user
            UserObject user = new UserObject();
            user.name = name;
            user.contactInfo = contact;
            user.userName = username;
            user.password = password;

            if (role == "Adminitrator")
                user.role = 'A';
            else if (role == "Clinician")
                user.role = 'C';

            //check for matching passwords and required information
            if (password != confirm_password)
            {
                error = "The entered passwords do not match.";
                error_type = MessageBoxIcon.Warning;
                return false;
            }

            //check for empty fields
            if (password.Equals("") || username.Equals("") || name.Equals(""))
            {
                error = "Please fill out all user information.";
                error_type = MessageBoxIcon.Warning;
                return false;
            }

            //try to create the user
            try
            {
                if (!Connection.Servicer.makeUser(user))
                {
                    error = "An error occured while creating the user.  Please try again.";
                    error_type = MessageBoxIcon.Error;
                    return false;
                }
            }
            catch (System.Net.WebException e)
            {
                error = e.Message;
                error_type = MessageBoxIcon.Error;
                return false;
            }

            return true;
        }
    public void reset()
    {
        _firstPreviousUserObject = new UserObject();
        _secondPreviousUserObject = new UserObject();
        _nextUserObject = new UserObject();

        _isFirstPreviousUserBuYao = false;
        _isFirstPreviousUserDaNi = false;
        _firstPreviousUserSendCards = new List<int>();
        _firstPreviousUserSendCardsType = CardInfo.CardPromptType.CARD_PROMPT_INVALID_TYPE;

        _secondPreviousUserSendCards = new List<int>();
        _isSecondPreviousUserBuYao = false;
        _isNextUserMustChuPai = false;
    }
Exemplo n.º 15
0
        public int AddPatient(UserObject user, String name, String ssn, DateTime dob, Char sex, Char hand, String contact, String address, String notes)
        {
            current_patient.name = name;
            current_patient.ssn = ssn;
            current_patient.dob = dob;
            current_patient.sex = sex;
            current_patient.handedness = hand;
            current_patient.ContactInfo = contact;
            current_patient.address = address;

            current_patient.ID = Connection.Servicer.addPatient(current_patient);
            this.AddNote(current_patient, user, notes);

            return current_patient.ID;
        }
Exemplo n.º 16
0
    /*
     * Pre-checks
     * 1) User has CharacterObject
     * If failed, boot to default or equivalent
     */
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["User"] == null)
        {
            Session["ErrorMessage"] = "You need to be logged in first";
            Response.Redirect("~/Login.aspx");
        }
        user = (UserObject)Session["User"];

        if (user.character == null)
        {
            Session["ErrorMessage"] = "You can create a Card Character here first before visiting the shop.";
            Response.Redirect("~/CreateAChar.aspx");
        }
        updateCharacterPanel();
    }
    public void setUserType(UserObject.Gender gender,UserObject.UserType userType, UserObject.OnLineType onlineType)
    {
        string imgName = "";
        string typeNameImg = "";

        if (gender == UserObject.Gender.MALE)
        {
            if (userType == UserObject.UserType.LANDOWNER)
            {
                if (onlineType == UserObject.OnLineType.ONLINE) imgName = "landowner_male_normal";
                if (onlineType == UserObject.OnLineType.OFFLINE) imgName = "landowner_male_gray";
                typeNameImg = "landowner_logo";
            }

            if (userType == UserObject.UserType.FARMER)
            {
                if (onlineType == UserObject.OnLineType.ONLINE) imgName = "farmer_male_normal";
                if (onlineType == UserObject.OnLineType.OFFLINE) imgName = "farmer_male_gray";
                typeNameImg = "farmer_logo";
            }
        }

        if (gender == UserObject.Gender.FEMALE)
        {
            if (userType == UserObject.UserType.LANDOWNER)
            {
                if (onlineType == UserObject.OnLineType.ONLINE) imgName = "landowner_female_normal";
                if (onlineType == UserObject.OnLineType.OFFLINE) imgName = "landowner_female_gray";
                typeNameImg = "landowner_logo";
            }

            if (userType == UserObject.UserType.FARMER)
            {
                if (onlineType == UserObject.OnLineType.ONLINE) imgName = "farmer_female_normal";
                if (onlineType == UserObject.OnLineType.OFFLINE) imgName = "farmer_female_gray";
                typeNameImg = "farmer_logo";
            }
        }

        SpriteRenderer userHeadFrontSpriteRender = _rotatedTransform.FindChild("userHeadFront").GetComponent<SpriteRenderer>();
        string frontHeaderImgFullName = "imgs/threePersonsPlay/userHead/" + imgName;
        userHeadFrontSpriteRender.sprite = Resources.Load<Sprite>(frontHeaderImgFullName);

        SpriteRenderer userTypeSpriteRender = this.transform.FindChild("userType").GetComponent<SpriteRenderer>();
        string userTypeImgFullName = "imgs/threePersonsPlay/userHead/" + typeNameImg;
        userTypeSpriteRender.sprite = Resources.Load<Sprite>(userTypeImgFullName);
    }
Exemplo n.º 18
0
 //protected Nullable<int> loggedInUserHospitalId = 0;
 protected void Page_Load(object sender, EventArgs e)
 {
     //Refresh the expiration on the user's authentication ticket
     //try
     {
         PagesFactory.InstantiatePageMap();
         Response.Cache.SetCacheability(HttpCacheability.NoCache);
         if (Session[ParameterNames.Session.LoggedInUser] == null)
         {
             if (IsPopUp())
             {
                 //Session[ParameterNames.Session.ExceptionString] = Messages.Error.YouMustBeLoggedIn;
                 PagesFactory.Transfer(PagesFactory.Pages.ErrorPage);
             }
             else
             {
                 Session[ParameterNames.Session.ErrorMessage] = Messages.Error.SessionExpired;
                 //Session[ParameterNames.Session.ErrorMessage] = Messages.Error.YouMustBeLoggedIn;
                 PagesFactory.Transfer(PagesFactory.Pages.LoginPage);
             }
         }
         else
         {
             loggedInUser = (UserObject)Session[ParameterNames.Session.LoggedInUser];
             loggedInUserId = (int)loggedInUser.UserId.Value;
             /*if (loggedInUser.ClientId != null && loggedInUser.ClientId.Value != null)
             {
                 loggedInUserClientId = (int)loggedInUser.ClientId.Value;
             }*/
             /*if (loggedInUser.HospitalId != null && loggedInUser.HospitalId.Value != null && (int)loggedInUser.HospitalId.Value != 0)
             {
                 loggedInUserHospitalId = (int)loggedInUser.HospitalId.Value;
             }*/
             if (Session[ParameterNames.Session.LoggedInUserRoleId] != null)
             {
                 loggedInUserRoleId = (int)Session[ParameterNames.Session.LoggedInUserRoleId];
             }
             Page_Load_Extended(sender, e);
         }
     }
     /*catch (Exception ex)
     {
         Session[ParameterNames.Session.ExceptionString] = ex.ToString();
         PagesFactory.Transfer(Constants.Pages.ErrorPage);
     }*/
 }
Exemplo n.º 19
0
 protected void btnResetPassword_Click(object sender, EventArgs e)
 {
     UserObject user = new UserObject();
     user.LoginName.Value = tbLoginName.Text;
     user.Load();
     if (user.IsLoaded && user.SecretQuestionId.Value != null && user.Answer.Value != null
         && (int)user.SecretQuestionId.Value == SecretQuestions1.SecretQuestionId
         && user.Answer.Value.ToString().Equals(tbAnswer.Text))
     {
         tbLoginName.Enabled = false;
         pnlPassword.Visible = true;
         pnlSecretQuestion.Visible = false;
     }
     else
     {
         SetErrorMessage("Please enter the correct information");
     }
 }
        protected override void LoadContent(GraphicInfo GraphicInfo, GraphicFactory factory ,IContentManager contentManager)
        {
            PhysxPhysicWorld PhysxPhysicWorld = World.PhysicWorld as PhysxPhysicWorld;

            base.LoadContent(GraphicInfo, factory, contentManager);
            {
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Blue), TextureType.DIFFUSE);

                BoxShapeDescription SphereGeometry = new BoxShapeDescription(1000, 5, 1000);
                PhysxPhysicObject PhysxPhysicObject = new PhysxPhysicObject(SphereGeometry,
                    Matrix.Identity, new Vector3(1000, 5, 1000));

                ForwardXNABasicShader shader = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                IObject obj = new IObject(fmaterial, simpleModel, PhysxPhysicObject);
                this.World.AddObject(obj);

                shader.BasicEffect.EnableDefaultLighting();
            }

            {
                ///very basic vehicle !!!
                ///no wheels also =P
                Vehicle Vehicle = new Vehicle(PhysxPhysicWorld.Scene);
                SimpleModel simpleModel = new SimpleModel(factory, "Model//block");
                simpleModel.SetTexture(factory.CreateTexture2DColor(1, 1, Color.Green));
                PhysxPhysicObject tmesh = new PhysxPhysicObject(Vehicle.VehicleBodyActor, new Vector3(5, 3, 7));

                ForwardXNABasicShader shader = new ForwardXNABasicShader(ForwardXNABasicShaderDescription.Default());
                ForwardMaterial fmaterial = new ForwardMaterial(shader);
                UserObject<Vehicle> obj = new UserObject<Vehicle>(fmaterial, simpleModel, tmesh,Vehicle);
                obj.OnUserUpdate += new Action<UserObject<StillDesign.PhysX.Samples.Vehicle>>(obj_OnUserUpdate);
                this.World.AddObject(obj);

            }

            BallThrowPhysx28 BallThrowBullet = new BallThrowPhysx28(this.World, GraphicFactory);
            this.AttachCleanUpAble(BallThrowBullet);

            this.World.CameraManager.AddCamera(new CameraFirstPerson(GraphicInfo));
        }
Exemplo n.º 21
0
    public static string ChangePwd(UserObject user,string oldpwd, string newpwd)
    {
        if(user.Password!=SecurityFactory.GetSecurity().Encrypt(oldpwd))
        {
            return "旧密码输入错误!";
        }
        bool result=DataAccessFactory.GetDataAccess().ExecuteSql("update table_users set c_pwd='"+SecurityFactory.GetSecurity().Encrypt(newpwd)+"' where id="+user.Id);
        if (result)
        {
            //BusLog log = new BusLog();
           // log.BusType = "修改密码";
           // log.Content = user.FullName+"修改自己的密码";
            //BusLogOperator.InitByLoginUser(log);
            //log.Operator=
            return string.Empty;

        }
        else
            return "修改密码失败!";
    }
        void obj_OnUserUpdate(UserObject<Vehicle> obj)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Space))
            {
                obj.UserData.Accelerate(10);
            }

            if (Keyboard.GetState().IsKeyDown(Keys.LeftControl))
            {
                obj.UserData.Accelerate(-10);
            }

            if (Keyboard.GetState().IsKeyDown(Keys.J))
            {
                obj.UserData.Turn(MathHelper.ToRadians(1));
            }

            if (Keyboard.GetState().IsKeyDown(Keys.H))
            {
                obj.UserData.Turn(MathHelper.ToRadians(-1));
            }
        }
Exemplo n.º 23
0
        public TestPatient(List<Script> tests, String batch_name, UserObject user, PatientObject patient, char sender)
        {
            InitializeComponent();
            this.patient = patient;
            this.user = user;
            this.t = new Test();
            this.sender = sender;

            TestEngine.Testing.TestScript s;
            test_scripts = new List<global::Movement.TestEngine.Testing.TestScript>();

            //Display the name of the batch as the form's title
            this.Text = "Running " + batch_name;

            //put the tests in a list in the form used by the test batch capture controle
            for (int x = 0; x < tests.Count; x++)
                test_scripts.Add(s = new global::Movement.TestEngine.Testing.TestScript(tests[x].scriptID, tests[x].scriptData));

            //callback functions for test completion and batch completion
            tbcc_test_patient.TestBatchComplete += new global::Movement.TestEngine.Testing.TestBatchCompleteHandler(testBatchCaptureControl1_TestBatchComplete);
            tbcc_test_patient.TestComplete += new global::Movement.TestEngine.Testing.TestCompleteHandler(testBatchCaptureControl1_TestComplete);
        }
    public IUserObject Spawn()
    {
        IUserObject spawnObject;

        if (this.deadObjectsPool.Count > 0)
        {
            spawnObject = this.deadObjectsPool.Dequeue();
            int currentHealth = spawnObject.GetHealth();
            spawnObject.AddHealth(this.initialHealth - currentHealth);
            if (typeof(IRectangle).IsAssignableFrom(spawnObject.GetShape().GetType()))
            {
                reSpawn((IRectangle)spawnObject.GetShape());
            }
            else if (typeof(ICircle).IsAssignableFrom(spawnObject.GetShape().GetType()))
            {
                reSpawn((ICircle)spawnObject.GetShape());
            }
        }
        else if (this.createdObjectCount >= this.objectUpperLimit)
        {
            throw new OverLimitSpawnException(this.createdObjectCount, this.objectUpperLimit);
        }
        else
        {
            if (this.createdObjectCount % 2 == 0)
            {
                spawnObject = new UserObject(this.initialHealth, spawnCircle());
            }
            else
            {
                spawnObject = new UserObject(this.initialHealth, spawnRectangle());
            }
            this.createdObjectCount++;
        }
        return(spawnObject);
    }
Exemplo n.º 25
0
        /// <summary>
        /// Updates a user account given the specified properties.
        /// </summary>
        /// <param name="attributeName">The name of the attribute to search by.</param>
        /// <param name="attributeValue">The value of the attribute to search using.</param>
        /// <param name="settings">The user settings.</param>
        public void UpdateUser(string attributeName, string attributeValue, UserSettings settings)
        {
            if (string.IsNullOrWhiteSpace(attributeName))
            {
                throw new ArgumentNullException(nameof(attributeName));
            }
            if (string.IsNullOrWhiteSpace(attributeValue))
            {
                throw new ArgumentNullException(nameof(attributeValue));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            var user = UserObject.FindAll(_adOperator, new Is(attributeName, attributeValue)).SingleOrDefault();

            if (user == null)
            {
                throw new ArgumentNullException($"Could not find user: {attributeValue}");
            }
            AddSettingsToUser(user, settings);
            user.Save();
        }
Exemplo n.º 26
0
        public UserModel ToUserModelFrom(UserObject userObject)
        {
            var user = new UserModel();

            user.FirstName  = userObject.FirstName;
            user.LastName   = userObject.LastName;
            user.Bio        = userObject.Bio;
            user.Email      = userObject.Email;
            user.UserName   = userObject.UserName;
            user.Avatar     = userObject.Avatar;
            user.Followers  = userObject.Followers.Select(ToUserModelFrom).ToList();
            user.Following  = userObject.Following.Select(ToUserModelFrom).ToList();
            user.Posts      = userObject.PublishedPosts.Select(ToPostModelFrom).ToList();
            user.LikedPosts = userObject.LikedPosts.Select(ToLikedPhotoModelFrom).ToList();
            user.SavedPosts = userObject.SavedPosts.Select(ToSavedPhotoModelModelFrom).ToList();

            user.UserName = user.FirstName + " " + user.LastName;

            user.Following?.ForEach(following =>
                                    user.FollowingPosts.AddRange(following.Posts.OrderByDescending(post => post.DateCreated).Take(10)));
            user.FollowingPosts?.OrderByDescending(post => post.DateCreated);

            return(user);
        }
Exemplo n.º 27
0
        public void GenerateLendReceipt(UserObject userObject, List <LendObject> lendObjects)
        {
            string location = "";

            if (Settings.Default.LocationNæstved == true)
            {
                location = "Næstved";
            }
            else if (Settings.Default.LocationRingsted == true)
            {
                location = "Ringsted";
            }
            else if (Settings.Default.LocationRoskilde == true)
            {
                location = "Roskilde";
            }
            else if (Settings.Default.LocationVordingborg == true)
            {
                location = "Vordingborg";
            }

            if (Settings.Default.SmsService == true)
            {
                string   itemsMsg   = "";
                DateTime returnDate = new DateTime();

                foreach (LendObject lendObject in lendObjects)
                {
                    returnDate = lendObject.ReturnDate;
                    itemsMsg  += lendObject.ItemObject.Type + " " + lendObject.ItemObject.Manufacturer + " " + lendObject.ItemObject.Model + " " + lendObject.ItemObject.Id + Environment.NewLine;
                }

                string msg = "Hej " + userObject.ZbcName + Environment.NewLine + Environment.NewLine + "Du har den " + DateTime.Now + " lånt følgende udstyr:" + Environment.NewLine + Environment.NewLine + itemsMsg + Environment.NewLine + "Dette udstyr skal være afleveret den " + returnDate + " senest!" + Environment.NewLine + Environment.NewLine + "Med Venlig Hilsen" + Environment.NewLine + "-Ubuy " + location; //Ubuy Rinsted kan ændres så man vælger location i config filen
                DALSms.Instance.SendSms(userObject.PhoneNumber, msg);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Read user object given the object id
        /// </summary>
        /// <param name="objectId">id of item to read</param>
        /// <returns>The requested user object or null if no matching user object is found.</returns>

        public static UserObject Read(int objectId)
        {
            if (ServiceFacade.UseRemoteServices)
            {
                Mobius.Services.Native.INativeSession       nativeClient = ServiceFacade.CreateNativeSessionProxy();
                Services.Native.NativeMethodTransportObject resultObject =
                    ServiceFacade.InvokeNativeMethod(nativeClient,
                                                     (int)Services.Native.ServiceCodes.MobiusUserObjectService,
                                                     (int)Services.Native.ServiceOpCodes.MobiusUserObjectService.Read1,
                                                     new Services.Native.NativeMethodTransportObject(new object[] { objectId }));
                ((System.ServiceModel.IClientChannel)nativeClient).Close();
                if (resultObject == null || resultObject.Value == null)
                {
                    return(null);
                }
                _uo = UserObject.DeserializeBinary((byte[])resultObject.Value);
                return(_uo);
            }

            else
            {
                return(UAL.UserObjectDao.Read(objectId));
            }
        }
Exemplo n.º 29
0
        public TestPatient(List <Script> tests, String batch_name, UserObject user, PatientObject patient, char sender)
        {
            InitializeComponent();
            this.patient = patient;
            this.user    = user;
            this.t       = new Test();
            this.sender  = sender;

            TestEngine.Testing.TestScript s;
            test_scripts = new List <global::Movement.TestEngine.Testing.TestScript>();

            //Display the name of the batch as the form's title
            this.Text = "Running " + batch_name;

            //put the tests in a list in the form used by the test batch capture controle
            for (int x = 0; x < tests.Count; x++)
            {
                test_scripts.Add(s = new global::Movement.TestEngine.Testing.TestScript(tests[x].scriptID, tests[x].scriptData));
            }

            //callback functions for test completion and batch completion
            tbcc_test_patient.TestBatchComplete += new global::Movement.TestEngine.Testing.TestBatchCompleteHandler(testBatchCaptureControl1_TestBatchComplete);
            tbcc_test_patient.TestComplete      += new global::Movement.TestEngine.Testing.TestCompleteHandler(testBatchCaptureControl1_TestComplete);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Fast insert/update of a single row including creation of the AnnotationDao object, transaction and header update
        /// </summary>
        /// <param name="vo"></param>
        /// <returns></returns>

        public static long InsertUpdateRowAndUserObjectHeader(AnnotationVo vo)
        {
            bool          newRow = vo.rslt_id <= 0;
            AnnotationDao dao    = new AnnotationDao();

            dao.BeginTransaction();
            long rsltId = dao.InsertUpdateRow(vo);

            dao.Commit();
            dao.Dispose();

            UserObject uo = UserObjectDao.ReadHeader(vo.mthd_vrsn_id);

            if (uo != null)
            {
                uo.UpdateDateTime = DateTime.Now;
                if (newRow)
                {
                    uo.Count++;
                }
                UserObjectDao.UpdateHeader(uo);
            }
            return(rsltId);
        }
Exemplo n.º 31
0
        public void ProcessRequest(HttpContext context)
        {
            var username = context.Request.Form["username"];
            var password = context.Request.Form["password"];

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var isValidLogin = DoLogin(username, password);

                if (isValidLogin)
                {
                    UserObject userObj    = GetUserObjectByName(username);
                    string     userString = JsonConvert.SerializeObject(userObj);

                    // MAKE TIMEOUT VARIABLE BASED ON APPSETTING.
                    var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now,
                                                               DateTime.Now.AddMinutes(30),
                                                               false, userString,
                                                               FormsAuthentication.FormsCookiePath);
                    string cookieString = FormsAuthentication.Encrypt(ticket);
                    var    cookie       = new HttpCookie(FormsAuthentication.FormsCookieName, cookieString);
                    context.Response.Cookies.Add(cookie);
                    context.Response.Write("OK");
                }

                else
                {
                    context.Response.Write("Login Failed");
                }
            }

            else
            {
                context.Response.Write("Login Invalid");
            }
        }
Exemplo n.º 32
0
        private static Table CreateTable(UserObject user1, UserObject user2, PdfFont bold, PdfFont regular)
        {
            Table table = new Table(UnitValue.CreatePercentArray(3)).UseAllAvailableWidth();

            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(bold).Add(new Paragraph("Name:")));
            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(regular).Add(new Paragraph(user1.Name)));
            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(regular).Add(new Paragraph(user2.Name)));

            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(bold).Add(new Paragraph("Id:")));
            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(regular).Add(new Paragraph(user1.Id)));
            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(regular).Add(new Paragraph(user2.Id)));

            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(bold).Add(new Paragraph("Reputation:")));
            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(regular)
                          .Add(new Paragraph(user1.Reputation.ToString())));
            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(regular)
                          .Add(new Paragraph(user2.Reputation.ToString())));

            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(bold).Add(new Paragraph("Job title:")));
            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(regular).Add(new Paragraph(user1.JobTitle)));
            table.AddCell(new Cell().SetBorder(Border.NO_BORDER).SetFont(regular).Add(new Paragraph(user2.JobTitle)));

            return(table);
        }
Exemplo n.º 33
0
        public DatabaseResponseWithData <IEnumerable <UserModel> > GetAllUsers()
        {
            IEnumerable <UserObject> users = null;
            var user = new UserObject {
                FirstName = "b", LastName = "v", Email = "*****@*****.**", Password = "******"
            };
            var post  = new PostObject();
            var saved = new SavedPostObject {
                Post = post
            };

            try {
                users = _realmRepository.GetAllUsers();
                //_realmRepository.AddUser ( user );
            } catch (RealmException realmEx) {
                return(new DatabaseResponseWithData <IEnumerable <UserModel> > (false, realmEx.Message));
            } catch (Exception ex) {
                return(new DatabaseResponseWithData <IEnumerable <UserModel> > (false, ex.Message));
            }

            var mapped = _realmDatabaseMapper.ToUserModelFrom(users.ToList());

            return(new DatabaseResponseWithData <IEnumerable <UserModel> > (true, null, mapped));
        }
Exemplo n.º 34
0
        public UserObject GetUserByZbcName(string zbcName)
        {
            UserObject userObject = null;

            try
            {
                ConnectMySql();
                MySqlCommand    cmd = new MySqlCommand("SELECT user_mifare, user_fname, user_lname, user_zbcname, user_phonenumber, user_isdisabled, user_isteacher, user_comment FROM users WHERE user_zbcname = '" + zbcName + "'", MysqlConnection);
                MySqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    userObject = new UserObject(rdr.GetString(1), rdr.GetString(2), rdr.GetString(3), rdr.GetString(0), rdr.GetInt32(4), Convert.ToBoolean(rdr.GetInt16(6)), false, Convert.ToBoolean(rdr.GetInt16(5)), rdr.GetString(7));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("############################FAILED: " + ex);
            }
            finally
            {
                MysqlConnection.Close();
            }
            return(userObject);
        }
Exemplo n.º 35
0
        public async Task UserDAO_ReadByIdAsync_SuccessfulRead
            (string username, string name,
            string email, string phoneNumber, string password, int disabled, string userType, string salt,
            long tempTimestamp, string emailCode, long emailCodeTimestamp, int loginFailures,
            long lastLoginFailTimestamp, int emailCodeFailures, int phoneCodeFailures)
        {
            //Arrange

            // Create a user for the test.
            UserRecord userRecord = new UserRecord(username, name, email,
                                                   phoneNumber, password, disabled, userType, salt,
                                                   tempTimestamp, emailCode, emailCodeTimestamp, loginFailures,
                                                   lastLoginFailTimestamp, emailCodeFailures, phoneCodeFailures);
            await userDAO.CreateAsync(userRecord).ConfigureAwait(false);


            //Act

            // Read the user's data.
            UserObject userObject = (UserObject)await userDAO.ReadByIdAsync(username).ConfigureAwait(false);

            // Check if it's correct and set the result accordingly.
            bool result = DataEquals(userRecord, userObject);

            //Assert

            // Result should be true.
            Assert.IsTrue(result);

            //CleanUp

            // Delete the user.
            await userDAO.DeleteByIdsAsync(new List <string> {
                username
            }).ConfigureAwait(false);
        }
Exemplo n.º 36
0
        /// <summary>
        /// Write a compound number list
        /// </summary>
        /// <returns></returns>

        public static int Write(
            CidList list,
            UserObject uo)
        {
            string fileName;

            string content = list.ToMultilineString();

            uo.Type = UserObjectType.CnList;
            if (Lex.IsNullOrEmpty(uo.Owner))             // set current user as owner if owner not defined
            {
                uo.Owner = SS.I.UserName;
            }

            if (Lex.IsNullOrEmpty(uo.ParentFolder))
            {
                throw new Exception("No parent folder for list");
            }

            uo.Content = content;
            uo.Count   = list.Count;
            UserObjectDao.Write(uo, uo.Id);

            if (uo.IsCurrentObject)
            {
                SessionManager.CurrentResultKeys = list.ToStringList();
                SessionManager.DisplayCurrentCount();
            }

            if (uo.HasDefinedParentFolder)
            {
                MainMenuControl.UpdateMruList(uo.InternalName);
            }

            return(list.Count);
        }
Exemplo n.º 37
0
        private void SavePermissions()
        {
            UserObject userObj = listBox1.SelectedItem as UserObject;

            RoleObject roleObj = listBox2.SelectedItem as RoleObject;

            userObj.User.DeletePermissionByRole(roleObj.Role);
            foreach (Control control in panel3.Controls)
            {
                GroupBox lb = control as GroupBox;
                if (lb != null)
                {
                    foreach (Control co in lb.Controls)
                    {
                        CheckBox cb = co as CheckBox;
                        if (cb != null && cb.Checked)
                        {
                            Permission per = cb.Tag as Permission;
                            userObj.User.AddPermission(per, roleObj.Role);
                        }
                    }
                }
            }
        }
Exemplo n.º 38
0
        public void UserDAO_ReadById_UnsuccessfulRead
            (string username, string name,
            string email, string phoneNumber, string password, int disabled, string userType, string salt,
            long tempTimestamp, string emailCode, long emailCodeTimestamp, int loginFailures,
            long lastLoginFailTimestamp, int emailCodeFailures, int phoneCodeFailures)
        {
            //Arrange

            UnitTestUserDAO userDAO = new UnitTestUserDAO();
            // Create a user for the test.
            UserRecord userRecord = new UserRecord(username, name, email,
                                                   phoneNumber, password, disabled, userType, salt,
                                                   tempTimestamp, emailCode, emailCodeTimestamp, loginFailures,
                                                   lastLoginFailTimestamp, emailCodeFailures, phoneCodeFailures);

            userDAO.Create(userRecord);
            bool result = false;

            //Act

            try
            {
                // Read the user's data.
                UserObject userObject = (UserObject)userDAO.ReadById(NonExistingUsername);
            }
            catch (ArgumentException)
            {
                // Catch exception and set the result true.
                result = true;
            }

            //Assert

            // Result should be true.
            Assert.IsTrue(result);
        }
Exemplo n.º 39
0
        /// <summary>
/// Setup the form with existing criteria
/// </summary>
/// <param name="qc"></param>

        void Setup(
            QueryColumn qc)
        {
            MetaTable mt = null;
            string    listName, mcName, tok, tok1, tok2, tok3, txt;
            int       i1;

            if (qc != null && qc.QueryTable != null)
            {
                mt = qc.QueryTable.MetaTable;
            }

            Text        = qc.ActiveLabel + " Criteria";
            Prompt.Text =
                "Choose one of the following " + qc.ActiveLabel + " criteria options.";

            Cid.Text            = "";
            CidListDisplay.Text = "";
            ListName.Text       = "";
            SavedListUo         = null;
            CidLo.Text          = "";
            CidHi.Text          = "";

            TempListName.Properties.Items.Clear();             // build dropdown of available temp list names
            foreach (TempCidList tl0 in SS.I.TempCidLists)
            {
                TempListName.Properties.Items.Add(tl0.Name);
            }
            TempListName.Text = "Current";

            Lex lex = new Lex();

            lex.OpenString(qc.Criteria);
            mcName = lex.GetUpper();               // metacolumn name
            if (Lex.Ne(mcName, qc.MetaColumnName)) // check if col name is first token
            {                                      // if not assume it's simply missing and that the operator is the first token
                lex.Backup();
                mcName = qc.MetaColumnName;
            }

            tok  = lex.GetUpper();            // operator
            tok1 = lex.GetUpper();            // following tokens */
            tok2 = lex.GetUpper();
            tok3 = lex.GetUpper();

            if (tok == "=" || tok == "")
            {
                tok1       = CompoundId.Format(tok1, mt);
                Cid.Text   = tok1;
                EQ.Checked = true;
            }

            else if (tok == "IN" && tok1.StartsWith("("))             // list saved with query only
            {
                InList.Checked = true;

                CidListString = qc.Criteria;
                i1            = CidListString.IndexOf("(");      // just get the list itself if parenthesized
                if (i1 >= 0)
                {
                    CidListString = CidListString.Substring(i1 + 1);
                }
                if (CidListString.EndsWith(")"))
                {
                    CidListString = CidListString.Substring(0, CidListString.Length - 1);
                }

                SetCidListDisplay();
            }

            else if (tok == "IN" && (Lex.Eq(Lex.RemoveAllQuotes(tok2), "CURRENT") ||
                                     Lex.StartsWith(tok2, UserObject.TempFolderNameQualified)))
            {             // temp list
                if (Lex.StartsWith(tok2, UserObject.TempFolderNameQualified))
                {
                    tok2 = tok2.Substring(UserObject.TempFolderNameQualified.Length);
                }
                TempListName.Text = tok2;
                TempList.Checked  = true;
            }

            else if (tok == "IN")             // saved list
            {
                SavedListUo = QueryEngine.ResolveCnListReference(tok2);
                if (SavedListUo != null)
                {
                    listName = SavedListUo.Name;
                }

                else
                {
                    listName = "Nonexistant list";                  // list deleted
                }
                ListName.Text     = listName;
                SavedList.Checked = true;
            }

            else if (tok == "BETWEEN")
            {
                tok1            = CompoundId.Format(tok1);
                CidLo.Text      = tok1;
                tok3            = CompoundId.Format(tok3);
                CidHi.Text      = tok3;
                Between.Checked = true;
            }
        }
Exemplo n.º 40
0
            private bool ModelSharingChanged(Action_ModelSharedWithUserIdsChanged _Action, Action <string> _ErrorMessageAction = null)
            {
                var OldHasStar = _Action.OldModelSharedWithUserIDs.Contains("*");
                var NewHasStar = _Action.ModelSharedWithUserIDs.Contains("*");

                //Check if old and new both have *
                if (OldHasStar && NewHasStar)
                {
                    return(true);
                }

                var UsersListJObject = new List <JObject>();

                if (OldHasStar || NewHasStar)
                {
                    if (!DatabaseService.ScanTable(UserDBEntry.DBSERVICE_USERS_TABLE(), out UsersListJObject, _ErrorMessageAction))
                    {
                        _ErrorMessageAction?.Invoke("InternalCalls->PubSub_To_AuthService->ModelSharingChanged: ScanTable has failed.");
                        return(false); //Internal error, return error for retrial.
                    }
                    if (UsersListJObject.Count == 0)
                    {
                        return(true);
                    }
                }

                var ToBeAddedUsers   = new List <string>();
                var ToBeRemovedUsers = new List <string>();

                //Check if old contains * but not the new
                if (OldHasStar && !NewHasStar)
                {
                    foreach (var UserObject in UsersListJObject)
                    {
                        if (UserObject != null && UserObject.ContainsKey(UserDBEntry.KEY_NAME_USER_ID))
                        {
                            var UserId = (string)UserObject[UserDBEntry.KEY_NAME_USER_ID];

                            if (!_Action.ModelSharedWithUserIDs.Contains(UserId))
                            {
                                ToBeRemovedUsers.Add(UserId);
                            }
                            else
                            {
                                ToBeAddedUsers.Add(UserId);
                            }
                        }
                    }
                }
                //Check if new contains * but not the old
                else if (!OldHasStar && NewHasStar)
                {
                    foreach (var UserObject in UsersListJObject)
                    {
                        if (UserObject != null && UserObject.ContainsKey(UserDBEntry.KEY_NAME_USER_ID))
                        {
                            ToBeAddedUsers.Add((string)UserObject[UserDBEntry.KEY_NAME_USER_ID]);
                        }
                    }
                }
                //None has star
                else
                {
                    var AlreadyFetchedUserObjects = new Dictionary <string, UserDBEntry>();
                    foreach (var OldUserId in _Action.OldModelSharedWithUserIDs)
                    {
                        if (!_Action.ModelSharedWithUserIDs.Contains(OldUserId))
                        {
                            //Just to check existence we only get the id as property
                            if (!DatabaseService.GetItem(UserDBEntry.DBSERVICE_USERS_TABLE(), UserDBEntry.KEY_NAME_USER_ID, new BPrimitiveType(OldUserId), new string[] { UserDBEntry.KEY_NAME_USER_ID }, out JObject UserObject, _ErrorMessageAction))
                            {
                                _ErrorMessageAction?.Invoke("InternalCalls->PubSub_To_AuthService->ModelSharingChanged: GetItem for " + UserDBEntry.KEY_NAME_USER_ID + ": " + OldUserId + " has failed.");
                                return(false); //Internal error, return error for retrial.
                            }
                            if (UserObject == null)
                            {
                                continue;
                            }

                            ToBeRemovedUsers.Add(OldUserId);
                        }
                    }
                    foreach (var NewUserId in _Action.ModelSharedWithUserIDs)
                    {
                        if (!_Action.OldModelSharedWithUserIDs.Contains(NewUserId))
                        {
                            if (!ToBeRemovedUsers.Remove(NewUserId))
                            {
                                //Just to check existence we only get the id as property
                                if (!DatabaseService.GetItem(UserDBEntry.DBSERVICE_USERS_TABLE(), UserDBEntry.KEY_NAME_USER_ID, new BPrimitiveType(NewUserId), new string[] { UserDBEntry.KEY_NAME_USER_ID }, out JObject UserObject, _ErrorMessageAction))
                                {
                                    _ErrorMessageAction?.Invoke("InternalCalls->PubSub_To_AuthService->ModelSharingChanged: GetItem for " + UserDBEntry.KEY_NAME_USER_ID + ": " + NewUserId + " has failed.");
                                    return(false); //Internal error, return error for retrial.
                                }
                                if (UserObject == null)
                                {
                                    continue;
                                }
                            }

                            ToBeAddedUsers.Add(NewUserId);
                        }
                    }
                }

                //Do not play with owner's rights
                ToBeAddedUsers.Remove(_Action.UserID);
                ToBeRemovedUsers.Remove(_Action.UserID);

                //No changes need to be made
                if (ToBeAddedUsers.Count == 0 && ToBeRemovedUsers.Count == 0)
                {
                    return(true);
                }

                var PathsRegex = new Tuple <string, List <string> >[]
                {
                    new Tuple <string, List <string> >("/3d/models/" + _Action.ModelID + "*", new List <string>()
                    {
                        "GET"
                    }),                                                                                                   //Only view access
                    new Tuple <string, List <string> >("/3d/models/" + _Action.ModelID + "/remove_sharing_from/user_id/{shareeUserId}", new List <string>()
                    {
                        "DELETE"
                    })
                };

                if (!UpdateUsersSharedModelsFields(ToBeAddedUsers, _Action.ModelID, Controller_Rights_Internal.EChangeUserRightsForModelType.Add, _ErrorMessageAction))
                {
                    return(false);
                }
                if (!UpdateUsersSharedModelsFields(ToBeRemovedUsers, _Action.ModelID, Controller_Rights_Internal.EChangeUserRightsForModelType.Delete, _ErrorMessageAction))
                {
                    return(false);
                }
                if (!UpdateRightsForUsersUponChangeOnSharing(ToBeAddedUsers, PathsRegex, Controller_Rights_Internal.EChangeUserRightsForModelType.Add, _ErrorMessageAction))
                {
                    return(false);
                }
                if (!UpdateRightsForUsersUponChangeOnSharing(ToBeRemovedUsers, PathsRegex, Controller_Rights_Internal.EChangeUserRightsForModelType.Delete, _ErrorMessageAction))
                {
                    return(false);
                }

                return(true);
            }
Exemplo n.º 41
0
 private void ListName_KeyPress(object sender, KeyPressEventArgs e)
 {
     SavedListUo = null;             // SavedListUo no longer valid
 }
Exemplo n.º 42
0
 private int UpdateFinding(int studyId,int findingId, int userId, string heading,string description,string impression,bool isTran,bool removeAudioData)
 {
     FindingObject finding = new FindingObject();
     if (findingId > 0)
     {
         finding.FindingId.Value = findingId;
         finding.Load();
         if (finding.IsLoaded && removeAudioData)
         {
             //if(finding.TextualTranscript.Value.Equals(findingText) return
             finding.AudioData.Value = null;
         }
     }
     else
     {
         finding.StudyId.Value = studyId;
         //adding this code to put in radiologist is and name.
         finding.AudioDate.Value = DateTime.Now;
         finding.AudioUserId.Value = userId;
         UserObject user = new UserObject();
         user.UserId.Value = userId;
         user.Load(userId);
         if (user.IsLoaded)
         {
             finding.AudioUserName.Value = user.Name.Value;
         }
     }
     if (isTran)
     {
         finding.TranscriptUserId.Value = userId;
         finding.TranscriptionDate.Value = DateTime.Now;
     }
     finding.TextualTranscript.Value = "<data><heading>" + heading + "</heading><description>" + description + "</description><impression>"
         + impression + "</impression></data>";
     finding.Save(userId);
     //very bad programming, but needs to be done for now.
     return int.Parse(finding.FindingId.Value.ToString());
 }
Exemplo n.º 43
0
 private bool UpdateUsersSharedModelsFields(List <string> _RelevantIdList, string _ModelID, Controller_Rights_Internal.EChangeUserRightsForModelType _Action, Action <string> _ErrorMessageAction)
 {
     foreach (var ChangeUserID in _RelevantIdList)
     {
         if (!Controller_AtomicDBOperation.Get().GetClearanceForDBOperation(InnerProcessor, UserDBEntry.DBSERVICE_USERS_TABLE(), ChangeUserID, _ErrorMessageAction))
         {
             _ErrorMessageAction?.Invoke("PubSub_To_AuthService->UpdateUsersSharedModelsFields: Atomic operation control has failed for " + UserDBEntry.KEY_NAME_USER_ID + ": " + ChangeUserID);
             return(false); //Retry
         }
         try
         {
             if (!DatabaseService.GetItem(
                     UserDBEntry.DBSERVICE_USERS_TABLE(),
                     UserDBEntry.KEY_NAME_USER_ID,
                     new BPrimitiveType(ChangeUserID),
                     UserDBEntry.Properties,
                     out JObject UserObject,
                     _ErrorMessageAction))
             {
                 _ErrorMessageAction?.Invoke("PubSub_To_AuthService->UpdateUsersSharedModelsFields: Get user database entry operation has failed. User ID: " + ChangeUserID);
                 return(false); //Retry
             }
             else if (UserObject != null)
             {
                 bool bUpdateDB        = false;
                 var  UserDeserialized = JsonConvert.DeserializeObject <UserDBEntry>(UserObject.ToString());
                 if (_Action == Controller_Rights_Internal.EChangeUserRightsForModelType.Add)
                 {
                     if (!UserDeserialized.UserSharedModels.Contains(_ModelID))
                     {
                         UserDeserialized.UserSharedModels.Add(_ModelID);
                         bUpdateDB = true;
                     }
                 }
                 else if (_Action == Controller_Rights_Internal.EChangeUserRightsForModelType.Delete)
                 {
                     if (UserDeserialized.UserSharedModels.Contains(_ModelID))
                     {
                         UserDeserialized.UserSharedModels.Remove(_ModelID);
                         bUpdateDB = true;
                     }
                 }
                 if (bUpdateDB)
                 {
                     if (!DatabaseService.UpdateItem(//Fire and forget is not suitable here since there are following calls after DB update which will change the DB structure
                             UserDBEntry.DBSERVICE_USERS_TABLE(),
                             UserDBEntry.KEY_NAME_USER_ID,
                             new BPrimitiveType(ChangeUserID),
                             JObject.Parse(JsonConvert.SerializeObject(UserDeserialized)),
                             out JObject _, EBReturnItemBehaviour.DoNotReturn, null, _ErrorMessageAction))
                     {
                         _ErrorMessageAction?.Invoke("PubSub_To_AuthService->UpdateUsersSharedModelsFields: Update user database entry operation has failed. User ID: " + ChangeUserID);
                         return(false); //Retry
                     }
                 }
             }
         }
        /// <summary>
        /// Add/update user object depends on whether identity of object is empty or not.<br />      
        /// </summary>
        /// <param name="user"></param>   
        public string SaveJson(UserObject user)
        {
            if (user == null)
                throw new BadRequestException(string.Format(CultureInfo.InvariantCulture,Resources.UserObjectCannotBeNull));

            string password = WebOperationContext.Current.IncomingRequest.Headers["password"];
            string passwordAnswer = WebOperationContext.Current.IncomingRequest.Headers["passwordAnswer"];

            try
            {
                membershipApi.Save(user, password, passwordAnswer);
                return user.UserId.ToString();
            }
            catch (ArgumentException ex)
            {
                throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, ex.Message));
            }
            catch (BadRequestException bad)
            {
                throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, bad.Message));
            }
            catch (FormatException formatEx)
            {
                throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, formatEx.Message));
            }
            catch (Exception exp)
            {
                Logger.Instance(this).Error(exp);
                throw new InternalServerErrorException();
            }
        }
        public override void ExecutePL(RootObject update, VkApi client, SqlConnection Con)
        {
            MessagesSendParams @params = new MessagesSendParams();
            var        chatId          = [email protected]_id;
            var        keyboardBuilder = new KeyboardBuilder().Clear();
            UserObject user            = new UserObject();

            try
            {
                SqlCommand getUser = new SqlCommand("SELECT equipment FROM Users WHERE chatId = @chatId;", Con);
                getUser.Parameters.AddWithValue("@chatId", chatId);
                SqlDataReader rgetUser = getUser.ExecuteReader();
                rgetUser.Read();
                user.equipment = JsonConvert.DeserializeObject <Equipment>(rgetUser["equipment"].ToString());
                rgetUser.Close();

                user.characteristics.intellect += user.equipment.head.characteristics.intellect;
                user.characteristics.intellect += user.equipment.chest.characteristics.intellect;
                user.characteristics.intellect += user.equipment.hands.characteristics.intellect;
                user.characteristics.intellect += user.equipment.legs.characteristics.intellect;
                user.characteristics.intellect += user.equipment.gadget.characteristics.intellect;

                user.characteristics.strength += user.equipment.head.characteristics.strength;
                user.characteristics.strength += user.equipment.chest.characteristics.strength;
                user.characteristics.strength += user.equipment.hands.characteristics.strength;
                user.characteristics.strength += user.equipment.legs.characteristics.strength;
                user.characteristics.strength += user.equipment.gadget.characteristics.strength;

                user.characteristics.agility += user.equipment.head.characteristics.agility;
                user.characteristics.agility += user.equipment.chest.characteristics.agility;
                user.characteristics.agility += user.equipment.hands.characteristics.agility;
                user.characteristics.agility += user.equipment.legs.characteristics.agility;
                user.characteristics.agility += user.equipment.gadget.characteristics.agility;

                keyboardBuilder
                .AddButton("⛑ Голова", "selectMyEquip", KeyboardButtonColor.Primary)
                .AddButton("🧥 Туловище", "selectMyEquip", KeyboardButtonColor.Primary)
                .AddLine()
                .AddButton("🧤 Руки", "selectMyEquip", KeyboardButtonColor.Primary)
                .AddButton("🥾 Ноги", "selectMyEquip", KeyboardButtonColor.Primary)
                .AddButton("💻 Гаджет", "selectMyEquip", KeyboardButtonColor.Primary)
                .AddLine()
                .AddButton("◀️ Назад", "selectHome", KeyboardButtonColor.Default)
                .SetInline();

                @params.Keyboard = keyboardBuilder.Build();
                @params.UserId   = chatId;
                @params.Message  = "Твоя космическая экипировка 👨‍🚀 \n" +
                                   "\n" +
                                   "⛑ Голова " + user.equipment.head.name + " (" +
                                   user.equipment.head.characteristics.intellect + " " +
                                   user.equipment.head.characteristics.strength + " " +
                                   user.equipment.head.characteristics.agility + ") \n" +
                                   "🧥 Туловище " +
                                   user.equipment.chest.name + " (" +
                                   user.equipment.chest.characteristics.intellect + " " +
                                   user.equipment.chest.characteristics.strength + " " +
                                   user.equipment.chest.characteristics.agility + ") \n" +
                                   "🧤 Руки " +
                                   user.equipment.hands.name + " (" +
                                   user.equipment.hands.characteristics.intellect + " " +
                                   user.equipment.hands.characteristics.strength + " " +
                                   user.equipment.hands.characteristics.agility + ") \n" +
                                   "🥾 Ноги " +
                                   user.equipment.legs.name + " (" +
                                   user.equipment.legs.characteristics.intellect + " " +
                                   user.equipment.legs.characteristics.strength + " " +
                                   user.equipment.legs.characteristics.agility + ") \n" +
                                   "💻 Гаджет " +
                                   user.equipment.gadget.name + " (" +
                                   user.equipment.gadget.characteristics.intellect + " " +
                                   user.equipment.gadget.characteristics.strength + " " +
                                   user.equipment.gadget.characteristics.agility + ") \n" +
                                   "\n" +
                                   "💪🏻 Сила: " + user.characteristics.strength + " \n" +
                                   "🎯 Ловкость: " + user.characteristics.agility + " \n" +
                                   "📖 Интеллект: " + user.characteristics.intellect + "";

                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
            }
            catch (Exception ee)
            {
                @params.Message     = "Ошибка в SelectMyEquipCommand: " + ee.Message;
                @params.Attachments = null;
                @params.Keyboard    = null;
                @params.UserId      = 59111081;
                @params.RandomId    = GetRandomId();
                client.Messages.SendAsync(@params);
            }
        }
Exemplo n.º 46
0
 public UserObj(UserObject userobj)
 {
     this.userobj = userobj;
 }
Exemplo n.º 47
0
        public static string DKN00To11_new(DataTable tblHeader, UserObject userObject, bool gg)
        {
            int       counter       = 0;
            DataTable dtResult      = new DataTable();
            DataTable dtSdhDownload = tblHeader.Clone();
            DataTable dt            = new DataTable();
            //            int result = 0;
            string _dk  = "";
            object rslt = null;

            using (Database db = new Database())
            {
                List <Parameter> prm = new List <Parameter>();
                string           _src, _cabId;
                int _tipeHI;
                db.BeginTransaction();
                // HEADERS
                db.Commands.Add(db.CreateCommand("usp_HI00_Download"));
                db.Commands.Add(db.CreateCommand("[usp_DKN_Download_newDKN]"));
                bool _cabRowID = tblHeader.Columns.Contains("HRowID");
                foreach (DataRow dr in tblHeader.Rows)
                {
                    try
                    {
                        _src    = Tools.isNull(dr["src"], "").ToString();
                        _tipeHI = (_src == "STR") ? 0 : 1;
                        _cabId  = Tools.isNull(dr["dari"], "").ToString().Trim();
                        if ((_cabId.Substring(0, 2) != userObject.CabangID) && (userObject.CabangID != "11"))
                        {
                            rslt = "Bukan HI Cabang anda.";
                        }

                        else
                        {
                            //add parameters
                            _dk = (Tools.isNull(dr["dk"], "").ToString() == "D") ? "K" : "D";
                            prm.Clear();
                            prm.Add(new Parameter("@PerusahaanRowID", SqlDbType.UniqueIdentifier, userObject.SelectedPerusahaanRowID));
                            if (_cabRowID == true)
                            {
                                prm.Add(new Parameter("@HRowID", SqlDbType.UniqueIdentifier, new Guid(Tools.isNull(dr["HRowID"], Guid.Empty).ToString())));
                            }
                            if (_cabRowID == true)
                            {
                                prm.Add(new Parameter("@DRowID", SqlDbType.UniqueIdentifier, new Guid(Tools.isNull(dr["DtRowID"], Guid.Empty).ToString())));
                            }
                            prm.Add(new Parameter("@HRecordID", SqlDbType.VarChar, Tools.isNull(dr["idhead"], "").ToString()));
                            prm.Add(new Parameter("@RecordID", SqlDbType.VarChar, Tools.isNull(dr["iddetail"], "").ToString()));
                            prm.Add(new Parameter("@Tanggal", SqlDbType.DateTime, dr["tanggal"]));
                            prm.Add(new Parameter("@NoDKN", SqlDbType.VarChar, Tools.isNull(dr["no_dkn"], "").ToString()));
                            prm.Add(new Parameter("@TipeHI", SqlDbType.TinyInt, _tipeHI));
                            prm.Add(new Parameter("@DK", SqlDbType.VarChar, _dk));
                            prm.Add(new Parameter("@Cabang", SqlDbType.VarChar, Tools.isNull(dr["cabang"], "").ToString()));
                            prm.Add(new Parameter("@CD", SqlDbType.VarChar, Tools.isNull(dr["cd"], "").ToString()));
                            prm.Add(new Parameter("@Src", SqlDbType.VarChar, Tools.isNull(dr["src"], "").ToString()));
                            prm.Add(new Parameter("@NoPerkiraan", SqlDbType.VarChar, Tools.isNull(dr["no_perk"], "").ToString()));
                            prm.Add(new Parameter("@Uraian", SqlDbType.VarChar, Tools.isNull(dr["uraian"], "").ToString()));
                            prm.Add(new Parameter("@Jumlah", SqlDbType.Money, (dr["jumlah"])));
                            prm.Add(new Parameter("@Dari", SqlDbType.VarChar, _cabId));
                            prm.Add(new Parameter("@Tolak", SqlDbType.Bit, (dr["ltolak"])));
                            prm.Add(new Parameter("@Alasan", SqlDbType.VarChar, Tools.isNull(dr["alasan"], "").ToString()));
                            prm.Add(new Parameter("@LastUpdatedBy", SqlDbType.VarChar, userObject.UserID));

                            db.Commands[0].Parameters = prm;
                            rslt = db.Commands[0].ExecuteScalar();
                            if ((Tools.isNull(rslt, "").ToString() == "Ok") && (_tipeHI == 1))
                            {
                                db.Commands[1].Parameters = prm;
                                rslt = db.Commands[1].ExecuteScalar();
                            }
                            if (Tools.isNull(rslt, "").ToString() == "Ok")
                            {
                                counter++;
                            }
                            else
                            {
                                rslt = rslt + "; NoDKN : " + Tools.isNull(dr["no_dkn"], "").ToString()
                                       + "; iddetail : " + Tools.isNull(dr["iddetail"], "").ToString();
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        rslt = "Catch error : " + ex.Message + ";  No.DKN : " + Tools.isNull(dr["no_dkn"], "").ToString()
                               + "; iddetail : " + Tools.isNull(dr["iddetail"], "").ToString();
                        break;
                    }
                }
                if (Tools.isNull(rslt, "").ToString() == "Ok")
                {
                    db.CommitTransaction();
                }
                else
                {
                    db.RollbackTransaction();
                }
            }
            return(Tools.isNull(rslt, "").ToString());
        }
        public void GetUserByInCorrectUserName()
        {
            _story = new Story("Get Memebers By IMembershipApi");

            _story.AsA("User")
              .IWant("to be able to get members, and give the incorrect users' userName")
              .SoThat("I can get Error Message");

            _story.WithScenario("Get members by ImembershipApi with the Incorrect userName")
               .Given("More than one correct GUID of users", () =>
               {
               })
               .When("I use the Get, I can get users ", () => _Uobject2 = _membershipApi.Get("Wild Name"))
               .Then("The return is null",
                       () =>
                       {
                           _Uobject2.ShouldBeNull();
                       });

            this.CleanUp();
        }
        public void GetUserByCorrectGuid()
        {
            _story = new Story("Get Memebers By IMembershipApi");

            _story.AsA("User")
              .IWant("to be able to get members, and give the correct users' GUID")
              .SoThat("I can do somethings for members");

            IDictionary<Guid, UserObject> _Users = new Dictionary<Guid, UserObject>();

            _story.WithScenario("Get members by ImembershipApi with the correct userName")
                .Given("More than one correct GUID of users", () =>
                {
                    _Uobject = _utils.CreateUserObject("Eunge Liu", true);

                    _membershipApi.Save(_Uobject, "123Hello", "123Hello");

                    createdObjectIds.Add(_Uobject.UserId);

                })
                .When("I use the Get, I can get users ", () => _Uobject2 = _membershipApi.Get(_Uobject.UserId))
                .Then("The User2 is User1",
                        () =>
                        {
                            _Uobject.ShouldEqual(_Uobject2);
                        });

            this.CleanUp();
        }
Exemplo n.º 50
0
        /// <summary>
        /// Convert labeled criteria to complex checking for errors
        /// </summary>
        /// <param name="criteria"></param>
        /// <param name="q"></param>
        /// <param name="complexCriteriaCtl"></param>

        public static bool ConvertEditableCriteriaToComplex(
            LabeledCriteria labeledCriteria,
            Query q,
            RichTextBox complexCriteriaCtl)
        {
            QueryTable  qt;
            QueryColumn qc;

            Lex lex = new Lex();

            lex.SetDelimiters(" , ; ( ) < = > <= >= <> != !> !< [ ]");
            lex.OpenString(labeledCriteria.Text);
            StringBuilder   sb      = new StringBuilder();
            PositionedToken lastTok = null;

            List <PositionedToken> tokens = new List <PositionedToken>();           // list of tokens seen

            int parenDepth = 0;

            while (true)
            {
                PositionedToken pTok = lex.GetPositionedToken();
                if (pTok == null)
                {
                    break;
                }

                tokens.Add(pTok);

                if (lastTok != null)
                {                 // include same white space between tokens
                    int wsBeg = lastTok.Position + lastTok.Text.Length;
                    sb.Append(labeledCriteria.Text.Substring(wsBeg, pTok.Position - wsBeg));
                }

                string tok = pTok.Text;

                if (MqlUtil.IsKeyWord(pTok.Text))                 // ok if keyword, operator, etc
                {
                    if (pTok.Text == "(")
                    {
                        parenDepth++;
                    }
                    else if (pTok.Text == ")")
                    {
                        parenDepth--;
                    }
                }

                else if (pTok.Text.StartsWith("'"))                 // string constant
                {
                    if (tokens.Count >= 3 && Lex.Eq(tokens[tokens.Count - 2].Text, "In") &&
                        Lex.Eq(tokens[tokens.Count - 1].Text, "List"))
                    {                     // saved list reference
                        UserObject uo = QueryEngine.ResolveCnListReference(tok);
                        if (uo != null)
                        {
                            tok = "CNLIST_" + uo.Id.ToString();
                        }
                        else
                        {
                            tok = "Nonexistant list";
                        }
                        tok = Lex.AddSingleQuotes(tok);
                    }
                }

                else if (Lex.IsDouble(pTok.Text))
                {
                }                                                     // numeric constant

                else if (tok == "[")
                {                 // translate editable structure reference
                    pTok = lex.GetPositionedToken();
                    if (!MatchToken(pTok, "Edit", complexCriteriaCtl))
                    {
                        return(false);
                    }

                    pTok = lex.GetPositionedToken();
                    if (!MatchToken(pTok, "Structure", complexCriteriaCtl))
                    {
                        return(false);
                    }

                    pTok = lex.GetPositionedToken();
                    tok  = Lex.RemoveSingleQuotes(pTok.Text.ToUpper());
                    if (!labeledCriteria.Structures.ContainsKey(tok))
                    {
                        ConvertLabeledCriteriaError("Structure \"" + pTok.Text + "\" not defined", pTok, complexCriteriaCtl);
                        return(false);
                    }
                    tok = Lex.AddSingleQuotes(labeledCriteria.Structures[tok]);                     // replace with chime

                    pTok = lex.GetPositionedToken();
                    if (!MatchToken(pTok, "]", complexCriteriaCtl))
                    {
                        return(false);
                    }
                }

                else if (Lex.Eq(pTok.Text, "structure_field"))
                {                 // check for user failing to define structure_field in structure search criteria
                    ConvertLabeledCriteriaError("\"Structure_field\" must be replaced with a real field name", pTok, complexCriteriaCtl);
                    return(false);
                }

                else              // must be a column reference or invalid token
                {                 // translate labeled column name
                    tok = TranslateLabeledColumnName(pTok, q, complexCriteriaCtl);
                    if (tok == null)
                    {
                        return(false);
                    }
                }

                sb.Append(tok);
                lastTok = pTok;
            }

            tokens = tokens;             // debug

            if (parenDepth != 0)         // parens balance?
            {
                if (parenDepth > 0)
                {
                    MessageBoxMx.ShowError("Unbalanced parentheses: left parentheses exceed right by " + parenDepth.ToString());
                }

                else
                {
                    MessageBoxMx.ShowError("Unbalanced parentheses: right parentheses exceed left by " + (-parenDepth).ToString());
                }

                if (complexCriteriaCtl != null)
                {
                    complexCriteriaCtl.Focus();
                }
                return(false);
            }

            q.ComplexCriteria = sb.ToString();             // store back in query
            return(true);
        }
Exemplo n.º 51
0
        /// <summary>
        /// Convert complex criteria to labeled form suitable for editing in complex criteria editor
        /// </summary>
        /// <param name="q"></param>
        /// <param name="structures">Dictionary of structure names & connection tables</param>

        public static LabeledCriteria ConvertComplexCriteriaToEditable(
            Query q,
            bool includeEditButtons)
        {
            bool insertBreaks = false;

            if (q.ComplexCriteria.IndexOf("\n") < 0)
            {
                insertBreaks = true;
            }

            Dictionary <string, string> tAliasMap = GetAliasMap(q);

            if (tAliasMap != null && !includeEditButtons)
            {             // fixup aliases properly first using editable criteria
                ConvertComplexCriteriaToEditable(q, true);
                tAliasMap = null;
            }

            Lex lex = new Lex();

            lex.SetDelimiters(" , ; ( ) < = > <= >= <> != !> !<");
            string criteria = q.ComplexCriteria;

            lex.OpenString(criteria);
            StringBuilder   sb      = new StringBuilder();
            PositionedToken lastTok = null;

            List <PositionedToken> tokens = new List <PositionedToken>();           // list of tokens seen

            LabeledCriteria lc = new LabeledCriteria();

            lc.Structures = new Dictionary <string, string>();

            while (true)
            {
                PositionedToken tok = lex.GetPositionedToken();
                if (tok == null)
                {
                    break;
                }

                tokens.Add(tok);

                if (lastTok != null)
                {                 // include same white space between tokens
                    int wsBeg = lastTok.Position + lastTok.Text.Length;
                    sb.Append(criteria.Substring(wsBeg, tok.Position - wsBeg));
                }

                QueryColumn qc = MqlUtil.GetQueryColumn(tok.Text, q); // see if token is column ref
                if (qc != null)
                {                                                     //query column, map to labeled columns
                    string label = GetUniqueColumnLabel(qc);

                    QueryTable qt = qc.QueryTable;
                    string     tName, cName;
                    MqlUtil.ParseColumnIdentifier(tok.Text, out tName, out cName);
                    if (tName != null && tName != "")                     // any table name supplied?
                    {
                        if (tAliasMap != null && tAliasMap.ContainsKey(tName.ToUpper()))
                        {
                            tName = tAliasMap[tName.ToUpper()];
                        }
                        label = tName + "." + label;
                    }

                    sb.Append(Lex.Dq(label));
                }

                else
                {                 // not a query column reference
                    string tokText = tok.Text;

                    string txt = Lex.RemoveSingleQuotes(tokText).ToUpper();
                    if (UserObject.IsCompoundIdListName(txt))
                    {
                        string     listName = null;
                        int        objectId = int.Parse(txt.Substring(7));
                        UserObject uo       = UserObjectDao.ReadHeader(objectId);
                        if (uo != null)
                        {
                            listName = uo.InternalName;
                        }
                        else
                        {
                            listName = "Unknown";
                        }
                        tokText = Lex.AddSingleQuotes(listName);
                    }

                    if (tokens.Count >= 5)
                    {                     // see if this is a chime string
                        string sFuncCand = tokens[tokens.Count - 5].Text.ToLower();
                        if ((Lex.Eq(sFuncCand, "SSS") || Lex.Eq(sFuncCand, "FSS") || Lex.Eq(sFuncCand, "MolSim")) &&
                            tokText.StartsWith("'") && tokText.EndsWith("'"))                             // single-quoted chime?
                        {
                            string sAlias = "S" + (lc.Structures.Count + 1).ToString();
                            lc.Structures[sAlias] = Lex.RemoveSingleQuotes(tokText);                             // save structure in dictionary
                            if (includeEditButtons)
                            {
                                tokText = "[Edit Structure " + sAlias + "]";                                 // use alias in labeled query
                            }
                            else
                            {
                                tokText = Lex.AddSingleQuotes(sAlias);
                            }
                        }
                    }

                    if ((Lex.Eq(tokText, "And") || Lex.Eq(tokText, "Or")) &&
                        tokens.Count >= 3 && !Lex.Eq(tokens[tokens.Count - 3].Text, "Between") &&
                        insertBreaks)
                    {
                        sb.Append("\n");                    // start new line for each and/or
                    }
                    sb.Append(tokText);                     // not query column identifier
                }

                lastTok = tok;
            }

            sb.Append(" ");             // include final space so additional text is black, also to get correct font
            lc.Text = sb.ToString();

            // If a table alias changes then update aliases & complex criteria but only if going
            // to editable text since ConvertEditableCriteriaToComplex fails otherwise.

            if (tAliasMap != null)
            {
                for (int qti = 0; qti < q.Tables.Count; qti++)
                {                 // set new table aliases
                    QueryTable qt    = q.Tables[qti];
                    string     alias = "T" + (qti + 1).ToString();
                    qt.Alias = alias;
                }

                ConvertEditableCriteriaToComplex(lc, q, null);                 // update q.ComplexCriteria also
            }

            return(lc);
        }
Exemplo n.º 52
0
 public bool CollectionExists(UserObject userObject)
 {
     return(CollectionExists(userObject.Name));
 }
Exemplo n.º 53
0
    private void UpdateVolumetricLine(UserObject uo)
    {
        try
        {
            float fCurrentAngle = Mathf.Round(uo.m_goVolumetricLine.transform.localEulerAngles.x);
            if (fCurrentAngle >= 180)
            {
                fCurrentAngle = fCurrentAngle - 180;
            }

            switch (uo.m_vlType)
            {
            case UserObject.VolumetricLineType.Back:
            {
                if (fCurrentAngle < 170)
                {
                    uo.m_goVolumetricLine.transform.Rotate(new Vector3(-NM_LINE_SPEED, 0f, 0f));
                }
                else
                {
                    uo.m_vlType = UserObject.VolumetricLineType.Front1;

                    if (m_bDemo)
                    {
                        CreatePopup(uo, "おい!");
                    }

                    uo.m_goVolumetricLine.transform.Rotate(new Vector3(NM_LINE_SPEED, 0f, 0f));
                }
            }
            break;

            case UserObject.VolumetricLineType.Front1:
            {
                uo.m_goVolumetricLine.transform.Rotate(new Vector3(NM_LINE_SPEED, 0f, 0f));
                if (uo.m_fLastAngle < fCurrentAngle)
                {
                    // 90度折り返し
                    uo.m_vlType = UserObject.VolumetricLineType.Front2;
                }
            }
            break;

            case UserObject.VolumetricLineType.Front2:
            {
                if (fCurrentAngle < 150)
                {
                    uo.m_goVolumetricLine.transform.Rotate(new Vector3(NM_LINE_SPEED, 0f, 0f));
                }
                else
                {
                    uo.m_vlType = UserObject.VolumetricLineType.Return;

                    uo.m_goVolumetricLine.transform.Rotate(new Vector3(-NM_LINE_SPEED, 0f, 0f));
                }
            }
            break;

            case UserObject.VolumetricLineType.Return:
            {
                if (fCurrentAngle < uo.m_fLastAngle)
                {
                    // 90度到達
                    uo.m_goVolumetricLine.transform.Rotate(new Vector3(-NM_LINE_SPEED, 0f, 0f));
                }
                else
                {
                    uo.m_vlType = UserObject.VolumetricLineType.Stop;
                }
            }
            break;
            }

            uo.m_fLastAngle = fCurrentAngle;
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.Message);
            System.Diagnostics.Trace.WriteLine(ex.StackTrace);
        }
    }
Exemplo n.º 54
0
        public static DataTable DBGetListHIByDate(UserObject _userObject, Guid perusahaanRowID, string cabangID, DateTime?fromDate, DateTime?toDate)
        {
            DataTable dt = DBGetListHIByDate(_userObject.SelectedPerusahaanRowID, _userObject.CabangID, perusahaanRowID, cabangID, fromDate, toDate);

            return(dt);
        }
Exemplo n.º 55
0
        public async Task <Result <bool> > VerifyEmailCodeAsync(string username, string inputCode, string ipAddress,
                                                                int currentNumExceptions)
        {
            try
            {
                bool emailVerificationSuccess = false;

                UserObject user = await _userManagementService.GetUserInfoAsync(username).ConfigureAwait(false);

                if (user.EmailCodeFailures >= Constants.MaxEmailCodeAttempts)
                {
                    _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString),
                                                 Constants.VerifyEmailOperation, username, ipAddress,
                                                 Constants.MaxEmailTriesReachedLogMessage).ConfigureAwait(false);

                    return(SystemUtilityService.CreateResult(Constants.MaxEmailTriesReachedUserMessage, emailVerificationSuccess, false));
                }

                long maxValidTimeSeconds = TimeUtilityService.TimespanToSeconds(Constants.EmailCodeMaxValidTime);
                long currentUnix         = TimeUtilityService.CurrentUnixTime();

                if (user.EmailCodeTimestamp + maxValidTimeSeconds < currentUnix)
                {
                    _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString),
                                                 Constants.VerifyEmailOperation, username, ipAddress,
                                                 Constants.EmailCodeExpiredLogMessage).ConfigureAwait(false);

                    return(SystemUtilityService.CreateResult(Constants.EmailCodeExpiredUserMessage, emailVerificationSuccess, false));
                }

                if (user.EmailCode.Equals(inputCode))
                {
                    emailVerificationSuccess = true;
                    await _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString),
                                                   Constants.VerifyEmailOperation, username, ipAddress).ConfigureAwait(false);

                    return(SystemUtilityService.CreateResult(Constants.VerifyEmailSuccessUserMessage, emailVerificationSuccess, false));
                }
                else
                {
                    _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString),
                                                 Constants.VerifyEmailOperation, username, ipAddress,
                                                 Constants.WrongEmailCodeMessage).ConfigureAwait(false);

                    await _userManagementService.IncrementEmailCodeFailuresAsync(username).ConfigureAwait(false);

                    return(SystemUtilityService.CreateResult(Constants.WrongEmailCodeMessage, emailVerificationSuccess, false));
                }
            }
            catch (Exception e)
            {
                _ = _loggingManager.LogAsync(DateTime.UtcNow.ToString(Constants.LoggingFormatString),
                                             Constants.VerifyEmailOperation, username, ipAddress, e.Message).ConfigureAwait(false);

                if (currentNumExceptions + 1 >= Constants.MaximumOperationRetries)
                {
                    await SystemUtilityService.NotifySystemAdminAsync($"{Constants.VerifyEmailOperation} failed a maximum number of times for {username}.", Constants.SystemAdminEmailAddress).ConfigureAwait(false);
                }

                return(SystemUtilityService.CreateResult(Constants.SystemErrorUserMessage, false, true));
            }
        }
Exemplo n.º 56
0
        public void CreateUserObjectToUpdateInDB(string userMifare, string fName, string lName, string zbcName, int phoneNumber, bool isDisabled, bool isTeacher)
        {
            UserObject userObject = new UserObject(fName, lName, zbcName, userMifare, phoneNumber, isTeacher, false, isDisabled, "");

            DALUser.Instance.UpdateUserInDB(userObject);
        }
 /// <summary>
 /// Add/update user object depends on whether identity of object is empty or not.<br />      
 /// </summary>
 /// <param name="user"></param>   
 public string SaveXml(UserObject user)
 {
     return SaveJson(user);
 }
Exemplo n.º 58
0
        public void SetUnknownSecurityParameters(UserObject user)
        {
            SqlCommand cmd = null;

            try
            {
                //user.Security = new UserSecurityObject();
                if (user.Security.Application.AuthSettings == null | user.Security.Application.AuthSettings == "")
                {
                    user.Security.Application.AuthSettings = "000";
                }
                if (user.Security.Application.AuthUser == null | user.Security.Application.AuthUser == "")
                {
                    user.Security.Application.AuthUser = "******";
                }
                if (user.Security.Main.AuthTask == null | user.Security.Main.AuthTask == "")
                {
                    user.Security.Main.AuthTask = "000";
                }
                if (user.Security.Main.AuthCustomer == null | user.Security.Main.AuthCustomer == "")
                {
                    user.Security.Main.AuthCustomer = "000";
                }
                if (user.Security.Main.AuthEmployee == null | user.Security.Main.AuthEmployee == "")
                {
                    user.Security.Main.AuthEmployee = "000";
                }
                if (user.Security.Costing.AuthCosting == null | user.Security.Costing.AuthCosting == "")
                {
                    user.Security.Costing.AuthCosting = "000";
                }
                if (user.Security.Costing.AuthFuel == null | user.Security.Costing.AuthFuel == "")
                {
                    user.Security.Costing.AuthFuel = "000";
                }
                if (user.Security.Costing.AuthFuelDelivery == null | user.Security.Costing.AuthFuelDelivery == "")
                {
                    user.Security.Costing.AuthFuelDelivery = "000";
                }
                if (user.Security.Costing.AuthFuelCorrection == null | user.Security.Costing.AuthFuelCorrection == "")
                {
                    user.Security.Costing.AuthFuelCorrection = "000";
                }
                if (user.Security.Vehicle.AuthVehicle == null | user.Security.Vehicle.AuthVehicle == "")
                {
                    user.Security.Vehicle.AuthVehicle = "000";
                }
                //user.Security.Material
                if (user.Security.Material == null)
                {
                    user.Security.Material = new UserSecurityMaterial();
                }
                if (user.Security.Material.AuthMaterial == null | user.Security.Material.AuthMaterial == "")
                {
                    user.Security.Material.AuthMaterial = "000";
                }
                if (user.Security.Material.AuthMaterialMaintenance == null | user.Security.Material.AuthMaterialMaintenance == "")
                {
                    user.Security.Material.AuthMaterialMaintenance = "000";
                }
                if (user.Security.Material.AuthMaterialMemo == null | user.Security.Material.AuthMaterialMemo == "")
                {
                    user.Security.Material.AuthMaterialMemo = "000";
                }
                if (user.Security.Material.AuthMaterialCategory == null | user.Security.Material.AuthMaterialCategory == "")
                {
                    user.Security.Material.AuthMaterialCategory = "000";
                }
                if (user.Security.Planning == null)
                {
                    user.Security.Planning = new UserSecurityPlanning();
                }
                if (user.Security.Planning.AuthPlanning == null | user.Security.Planning.AuthPlanning == "")
                {
                    user.Security.Planning.AuthPlanning = "000";
                }

                this.Save(user);
            }
            catch (Exception exception1)
            {
                Exception innerException = exception1;
                throw new Exception(MethodBase.GetCurrentMethod().Name, innerException);
            }
            finally
            {
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                cmd = null;
            }
        }
Exemplo n.º 59
0
        /// <summary>
        /// Be sure that the specified internal object matches the read permissions of the supplied user object
        /// </summary>
        /// <param name="uoId"></param>
        /// <param name="acl"></param>
        /// <param name="internalObjectNameToMatch"></param>
        /// <returns></returns>

        public static bool AssignMatchingReadAccess(
            int uoId,
            AccessControlList acl,
            string internalObjectNameToMatch)
        {
            AccessControlList acl2;
            UserObjectType    uoType;
            int uoId2;

            if (!acl.IsShared)
            {
                return(false);                           // source object not shared
            }
            string objName = internalObjectNameToMatch;

            if (!UserObject.ParseObjectTypeAndIdFromInternalName(objName, out uoType, out uoId2))
            {
                DebugLog.Message("Can't parse object name: " + objName);
                return(false);
            }

            UserObject uo2 = UserObjectDao.ReadHeader(uoId2);

            if (uo2 == null)
            {
                DebugLog.Message("Can't read object: " + internalObjectNameToMatch + ", " + uoId2);
                return(false);
            }

            acl2 = AccessControlList.Deserialize(uo2);

            if (acl.IsPublic)
            {
                if (acl2.IsPublic)
                {
                    return(false);
                }
            }

            // check if list of readers matches

            bool modified = false;

            foreach (AclItem item in acl.Items)
            {
                if (!item.ReadIsAllowed)
                {
                    continue;
                }
                PermissionEnum permissions = acl2.GetUserPermissions(item.AssignedTo); // get permissions for corresponding user/group for obj2
                if (!Permissions.ReadIsAllowed(permissions))                           // add read if doesn't have
                {
                    if (item.IsPublic)
                    {
                        acl2.AddPublicReadItem();
                    }
                    else
                    {
                        acl2.AddReadUserItem(item.AssignedTo);
                    }
                    modified = true;
                }
            }

            if (modified)                                                               // update in db if modified
            {
                DebugLog.Message("AssignMatchingReadAccess: " + uoId + ", " + objName); // debug

                acl2.Serialize(uo2);
                UserObjectDao.UpdateHeader(uo2, false, false);
                return(true);
            }

            else
            {
                return(false);
            }
        }
Exemplo n.º 60
0
 public Boolean AddNote(PatientObject patient, UserObject user, String data)
 {
     return Connection.Servicer.addPatientNote(patient, user, data);
 }