private ConfirmationEmailTemplate GetAdminEmailTemplate(string adminName, string adminEmail, UserDetail userInfo, Pollinator.DataAccess.PolinatorInformation pollinator)
    {
        String path = Request.PhysicalApplicationPath + "\\EmailTemplates\\RegisterEmailAdmin.html";
        Uri uri = HttpContext.Current.Request.Url;
        string webAppUrl = uri.GetLeftPart(UriPartial.Authority); //Return both host and port

        using (StreamReader reader = File.OpenText(path))
        {
            String content = reader.ReadToEnd();  // Load the content from your file...
            content = content.Replace("{AdminName}", adminName);
            content = content.Replace("{RegisterName}", userInfo.FirstName);
            content = content.Replace("{UserType}", "PREMIUM");
            content = content.Replace("{ShareMapUrl}", webAppUrl + "/Pollinator/ShareMap.aspx");
            content = content.Replace("{OrganizationName}", pollinator.OrganizationName);
            content = content.Replace("{PhoneNumber}", userInfo.PhoneNumber);
            content = content.Replace("{LandscapeStreet}", pollinator.LandscapeStreet);
            content = content.Replace("{LandscapeCity}", pollinator.LandscapeCity);
            content = content.Replace("{LandscapeState}", pollinator.LandscapeState);
            content = content.Replace("{LandscapeZipcode}", pollinator.LandscapeZipcode);
            content = content.Replace("{PollinatorSize}", pollinator.PollinatorSize.ToString());
            content = content.Replace("{PollinatorType}", pollinator.PollinatorType.ToString());
            content = content.Replace("{LogonLink}", webAppUrl + "/Pollinator/Account/Login");

            var membership = System.Web.Security.Membership.GetUser(userInfo.UserId);

            var emailTemplate = new ConfirmationEmailTemplate();
            emailTemplate.EmailTo = adminEmail;
            emailTemplate.EmailFrom = Utility.EmailConfiguration.WebMasterEmail;
            emailTemplate.Subject = "Thank you for registering with S.H.A.R.E!";
            emailTemplate.EmailBodyTemplate = content;

            return emailTemplate;
        }
    }
Esempio n. 2
0
 public ActionResult About()
 {
     ViewBag.Message = "Your application description page.";
     UserDetail user = new UserDetail();
     user = userService.AddUser(user);
     return View();
 }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        UserDetail ud = new UserDetail();
        try
        {
            string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");
            DataTable dt = ud.CheckStudent(txtUsername.Text, hashedPassword, ddlFaculty.SelectedItem.Value, ddlSemester.SelectedItem.Value);

            if (dt.Rows.Count > 0)
            {
                Session["Student"] = txtUsername.Text;
                Session["Faculty"] = ddlFaculty.SelectedItem.Value;
                Session["Semester"] = ddlSemester.SelectedItem.Value;
                Response.Redirect("MyProfile.aspx");
            }
            else
            {
                ltrMessage.Text = "Invallid User or Password!";
            }
        }
        catch (Exception ex)
        {
            ltrMessage.Text = ex.Message;
        }
    }
 protected void btnSearchById_Click(object sender, EventArgs e)
 {
     try
     {
         UserDetail ud = new UserDetail();
         DataTable dt = ud.SearchStudentByID(txtStudentID.Text);
         txtStudentName.Text = dt.Rows[0]["Name"].ToString();
         txtRollNumber.Text = dt.Rows[0]["RollNumber"].ToString().Trim();
         txtUsername.Text = dt.Rows[0]["Username"].ToString();
         ddlFaculty.Text = dt.Rows[0]["Faculty"].ToString();
         ddlSemester.Text = dt.Rows[0]["Semester"].ToString();
         txtEmail.Text = dt.Rows[0]["Email"].ToString();
         lblMessage.ForeColor = System.Drawing.Color.Black;
         lblMessage.Text = "";
     }
     catch (Exception)
     {
         lblMessage.ForeColor = System.Drawing.Color.Red;
         lblMessage.Text = "Invalid Student ID";
         txtStudentName.Text = "";
         txtRollNumber.Text = "";
         txtUsername.Text = "";
         ddlSemester.Text = "";
         txtEmail.Text = "";
     }
 }
 protected void btnUpdate_Click(object sender, EventArgs e)
 {
     try
     {
         UserDetail ud = new UserDetail();
         DataTable dt = ud.SearchStudentByID(txtStudentID.Text);
         if (dt.Rows.Count < 1)
         {
             lblMessage.ForeColor = System.Drawing.Color.Red;
             lblMessage.Text = "Invalid Student ID";
             lblMessage.Text = "Invalid Student ID";
         }
       
         else {
             ud.UpdateStudent(txtStudentName.Text, txtRollNumber.Text, txtUsername.Text, ddlFaculty.SelectedItem.Value, ddlSemester.SelectedItem.Value, txtEmail.Text, txtStudentID.Text);
             lblMessage.ForeColor = System.Drawing.Color.Black;
             lblMessage.Text = "Successfully Updated!";
             txtStudentID.Text = "";
             txtStudentName.Text = "";
             txtRollNumber.Text = "";
             txtUsername.Text = "";
             txtEmail.Text = "";
             txtStudentID.Focus();
         }
         
     }
     catch(Exception){
         lblMessage.ForeColor = System.Drawing.Color.Red;
         lblMessage.Text = "Record Cannot be Updated";
     }
 }
Esempio n. 6
0
    public UserDetail FromCookie()
    {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

            UserDetail userDetail = new UserDetail();

            userDetail = UserDetail.FromString(ticket.UserData);

            return userDetail;
    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        // Default UserStore constructor uses the default connection string named: DefaultConnection
        var userStore = new UserStore<IdentityUser>();

        //Set ConnectionString to GarageConnectionString
        userStore.Context.Database.Connection.ConnectionString =
            System.Configuration.ConfigurationManager.ConnectionStrings["GarageConnectionString"].ConnectionString;
        var manager = new UserManager<IdentityUser>(userStore);

        //Create new user and try to store in DB.
        var user = new IdentityUser { UserName = txtUserName.Text };

        if (txtPassword.Text == txtConfirmPassword.Text)
        {
            try
            {
                IdentityResult result = manager.Create(user, txtPassword.Text);
                if (result.Succeeded)
                {
                    UserDetail userDetail = new UserDetail
                    {
                        Address = txtAddress.Text,
                        FirstName = txtFirstName.Text,
                        LastName = txtLastName.Text,
                        Guid = user.Id,
                        PostalCode = Convert.ToInt32(txtPostalCode.Text)
                    };

                    UserDetailModel model = new UserDetailModel();
                    model.InsertUserDetail(userDetail);

                    //Store user in DB
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                    //If succeedeed, log in the new user and set a cookie and redirect to homepage
                    authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                    Response.Redirect("~/Index.aspx");
                }
                else
                {
                    litStatusMessage.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                litStatusMessage.Text = ex.ToString();
            }
        }
        else
        {
            litStatusMessage.Text = "Passwords must match!";
        }
    }
        public void Update(UserDetail userDetail)
        {
            //Fetch object from db
            UserDetail u = db.UserDetails.Find(userDetail.Id);

            u.Address = userDetail.Address;
            u.FirstName = userDetail.FirstName;
            u.LastName = userDetail.LastName;
            u.PostalCode = userDetail.PostalCode;

            db.SaveChanges();
        }
        public static string InsertUser(UserDetail e)
        {
            dataContext.UserDetails.Add(e);
            try {
                dataContext.SaveChanges();
            }

            catch(Exception e1)
            {
                Console.WriteLine(e1);
            }
            return "success";
        }
Esempio n. 10
0
        private void bindingNavigatorEditItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count < 1)
                return;

            var srNo = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["Id"].Value);

            _userDetail = uniDb.UserDetails.Single(x => x.Id == srNo);

            ResetAndBindPageControls();

            SetControlNonEditForAdmin();
        }
Esempio n. 11
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Token = Member.AdminToken;
            if (Token.IsEmpty())
            {
                filterContext.Result =
                    new RedirectResult(Url.Action("Index", "Login",
                        new {returnurl = HttpUtility.UrlEncode(Request.Url.ToString())}));

                return;
            }

            LoginUserDetail = Member.GetLoginMember(Token);
            ViewData["UserName"] = LoginUserDetail.Nick;
            base.OnActionExecuting(filterContext);
        }
 protected void btnCreateMember_Click(object sender, EventArgs e)
 {
     UserDetail ud = new UserDetail();
     try
     {
         string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");
         ud.SaveMember(txtMemberID.Text, txtUsername.Text, hashedPassword);
         ltrMessage.Text = "Member Successfully Created";
         txtMemberID.Text = "";
         txtUsername.Text = "";
         txtPassword.Text = "";
         txtMemberID.Focus();
         }
     catch(Exception){
         ltrMessage.Text = "Member Already Exists";
     }
 }
Esempio n. 13
0
        public static bool AddAccountDetails(string userName, string password,bool isCurrent)
        {
            using(MagDBEntities dbentities = new MagDBEntities())
            {
                UserDetail detail = new UserDetail();
                detail.UserName = userName;
                detail.Password=password;
                dbentities.UserDetails.Add(detail);
                dbentities.SaveChanges();

                AccountInformation info = new AccountInformation();
                info.IsCurrent=isCurrent;
                info.Balance=10000;
                info.UserId=detail.Id;
                dbentities.AccountInformations.Add(info);
                dbentities.SaveChanges();
                return true;
            }
        }
        public Task<IEnumerable<string>> Post(string name, string address)
        {
            try
            {

                if (Request.Content.IsMimeMultipartContent())
                {
                    string fullPath = HttpContext.Current.Server.MapPath("~/uploads");
                    MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(fullPath);
                    var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
                    {
                        if (t.IsFaulted || t.IsCanceled)
                            throw new HttpResponseException(HttpStatusCode.InternalServerError);
                        var fileInfo = streamProvider.FileData.Select(i =>
                        {
                            var info = new FileInfo(i.LocalFileName);
                            UserDetail ud = new UserDetail();
                            byte[] a = File.ReadAllBytes(info.FullName);

                            //img.productID = productid;
                            ud.fname = name;
                            ud.address = address;
                            ud.pic = a;

                            ImageRepository.updateImage(ud);
                            return "File uploaded successfully!";
                        });
                        return fileInfo;
                    });
                    return task;
                }
                else
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
                }

            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
                return null;
            }
        }
 protected void btnCreateStudent_Click(object sender, EventArgs e)
 {
     try
     {
         UserDetail ud = new UserDetail();
         string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtRollNumber.Text, "SHA1");
         ud.AddStudent(txtStudentID.Text, txtStudentName.Text, txtRollNumber.Text, txtRollNumber.Text, hashedPassword, ddlFaculty.SelectedItem.Value, ddlSemester.SelectedItem.Value, txtEmail.Text, "Student/" + FileUpload1.FileName);
         FileUpload1.SaveAs(Server.MapPath("~/Student/" + FileUpload1.FileName));
         ltrMessage.Text = "Saved Successfully!";
         txtStudentID.Text = "";
         txtStudentName.Text = "";
         txtRollNumber.Text = "";
         txtEmail.Text = "";
         txtStudentID.Focus();
     }
     catch(Exception){
         ltrMessage.Text = "Student Already Exists";
     }
 }
Esempio n. 16
0
    public void SendRegisterEmail(UserDetail userInfo, Pollinator.DataAccess.PolinatorInformation pollinator)
    {
        var emails = new List<ConfirmationEmailTemplate>();

        var userEmailTemplate = GetUserEmailTemplate(userInfo, pollinator);
        emails.Add(userEmailTemplate);

        var Administrators = new List<string>();
        Administrators.Add("Truong"); //Dummy data, must be replaced with real Admin name

        foreach(var admin in Administrators)
        {
            string adminEmail = "*****@*****.**";//DUMMY data, must replaced with real data of Admin user

            var adminEmailTemplate = GetAdminEmailTemplate(admin, adminEmail, userInfo, pollinator);
            emails.Add(adminEmailTemplate);
        }

        Session["Emails"] = emails;
    }
 protected void btnDelete_Click(object sender, EventArgs e)
 {
     try
     {
         UserDetail ud = new UserDetail();
         ud.DeleteStudent(txtStudentID.Text);
         lblMessage.Text = "Successfully Deleted!";
         txtStudentID.Text = "";
         txtStudentName.Text = "";
         txtRollNumber.Text = "";
         txtUsername.Text = "";
         txtEmail.Text = "";
         txtStudentID.Focus();
     }
     catch (Exception)
     {
         lblMessage.ForeColor = System.Drawing.Color.Red;
         lblMessage.Text = "Record Cannot be Deleted";
     }
 }
Esempio n. 18
0
        public async Task <ActionResult> Register(RegisterViewModel userViewModel, params string[] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = userViewModel.Email, Email = userViewModel.Email, EmailConfirmed = true
                };
                var adminresult = await UserManager.CreateAsync(user, userViewModel.Password);

                //Add User to the selected Roles
                if (adminresult.Succeeded)
                {
                    var result = await UserManager.AddToRolesAsync(user.Id, "Employee");

                    if (!result.Succeeded)
                    {
                        ModelState.AddModelError("", result.Errors.First());
                        ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
                        return(View());
                    }
                    UserDetail deets = new UserDetail()
                    {
                        UserID    = user.Id,
                        FirstName = userViewModel.FirstName,
                        LastName  = userViewModel.LastName
                    };
                    LMSEntities ctx = new LMSEntities();
                    ctx.UserDetails.Add(deets);
                    ctx.SaveChanges();
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                    ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
                    return(View());
                }
                return(RedirectToAction("Login"));
            }
            ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
            return(View());
        }
Esempio n. 19
0
        public async Task <IActionResult> Register(AccountVM register)
        {
            if (ModelState["Fullname"].ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid ||
                ModelState["RegisterUsername"].ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid || ModelState["Email"].ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid ||
                ModelState["RegisterPassword"].ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid ||
                ModelState["ConfirmPassword"].ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid)
            {
                register.Bio = _db.Bios.FirstOrDefault();
                return(PartialView("_RegisterPartialView", register));
            }
            AppUser user = new AppUser
            {
                FullName = register.Fullname,
                UserName = register.RegisterUsername,
                Email    = register.Email
            };
            IdentityResult identityResult = await _userManager.CreateAsync(user, register.RegisterPassword);

            if (!identityResult.Succeeded)
            {
                foreach (var error in identityResult.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
                register.Bio = _db.Bios.FirstOrDefault();
                return(PartialView("_RegisterPartialView", register));
            }
            UserDetail userDetail = new UserDetail
            {
                AppUserId = user.Id
            };

            _db.UserDetails.Add(userDetail);
            await _userManager.AddToRoleAsync(user, Helper.Roles.Member.ToString());

            await _signInManager.SignInAsync(user, false);

            await _db.SaveChangesAsync();

            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 20
0
        public UserDetail GetLandloardEmail(string landlordEmail)
        {
            objDataAccess = DataAccess.NewDataAccess();
            objDbCommand  = objDataAccess.GetCommand(true, IsolationLevel.ReadCommitted);
            DbDataReader objDbDataReader = null;
            UserDetail   objUserDtl      = null;

            objDbCommand.AddInParameter("LandloardId", landlordEmail);



            try
            {
                objDbDataReader = objDataAccess.ExecuteReader(objDbCommand, "ams.uspGetLandloardEmail",
                                                              CommandType.StoredProcedure);
                if (objDbDataReader.HasRows)
                {
                    //DocumentBiz.GetApplicantDocuments(applicantId);
                    while (objDbDataReader.Read())
                    {
                        objUserDtl = new UserDetail();
                        BuildModel(objDbDataReader, objUserDtl);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error : " + ex.Message);
            }
            finally
            {
                if (objDbDataReader != null)
                {
                    objDbDataReader.Close();
                }
                objDataAccess.Dispose(objDbCommand);
            }


            return(objUserDtl);
        }
Esempio n. 21
0
        public UserDetail GetUserBasicInfo(User objUser)
        {
            objDataAccess = DataAccess.NewDataAccess();
            objDbCommand  = objDataAccess.GetCommand(true, IsolationLevel.ReadCommitted);
            DbDataReader objDbDataReader = null;
            UserDetail   objUserDtl      = null;

            objDbCommand.AddInParameter("EmailAsUserID", objUser.Email);
            objDbCommand.AddInParameter("MobileNoAsUserID", objUser.MobileNo);
            objDbCommand.AddInParameter("Password", objUser.Password);

            try
            {
                objDbDataReader = objDataAccess.ExecuteReader(objDbCommand, "ams.uspGetAuthoriseUserBasicInfo",
                                                              CommandType.StoredProcedure);
                if (objDbDataReader.HasRows)
                {
                    //DocumentBiz.GetApplicantDocuments(applicantId);
                    while (objDbDataReader.Read())
                    {
                        objUserDtl = new UserDetail();
                        BuildModel(objDbDataReader, objUserDtl);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error : " + ex.Message);
            }
            finally
            {
                if (objDbDataReader != null)
                {
                    objDbDataReader.Close();
                }
                objDataAccess.Dispose(objDbCommand);
            }


            return(objUserDtl);
        }
        public async Task <IEnumerable <UserDetail> > GetUserDetail()
        {
            try
            {
                UserDetail        userDetail  = new UserDetail();
                List <UserDetail> userDetails = new List <UserDetail>();
                List <User>       users       = await _context.Users.Find(_ => true).ToListAsync();

                List <Question> questions = await _context.Questions.Find(_ => true).ToListAsync();

                foreach (User u in users)
                {
                    userDetail.internalId = u.internalId;
                    userDetail.surveyId   = u.surveyId;
                    userDetail.userName   = u.userName;
                    userDetail.userPhone  = u.userPhone;
                    userDetail.userEmail  = u.userEmail;
                    userDetail.optIn      = u.optIn;
                    List <Response> responses = await _context.Responses.Find(r => r.userId == u.internalId).ToListAsync();

                    List <UserDetailResponse> udResponses = new List <UserDetailResponse>();
                    foreach (Question q in questions)
                    {
                        Response response = await _context.Responses.Find(s => s.questionId == q.questionId).SingleOrDefaultAsync();

                        UserDetailResponse udResponse = new UserDetailResponse();
                        udResponse.questionDesc = q.questionDesc;
                        udResponse.questionType = q.questionType;
                        udResponse.choice       = response.choice;
                        udResponses.Add(udResponse);
                    }
                    userDetail.responses = udResponses;
                    userDetails.Add(userDetail);
                }
                return(userDetails);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 23
0
        //OLD method can be deleted when cleaning up
        public static string GetUserDetail()
        {
            string paraphrase = "123medicarepass";
            string email      = System.Web.HttpContext.Current.User.Identity.Name;

            var userService = ApplicationContext.Current.Services.MemberService;
            //Get the member from their email address
            var        amember = userService.GetByEmail(email);
            UserDetail ud      = new UserDetail();

            ud.UserFirstName = amember.GetValue("firstName").ToString();
            ud.UserLastName  = amember.GetValue("lastName").ToString();
            ud.UserEmail     = email;

            string st = amember.GetValue("state").ToString();

            if (st == "IND")
            {
                st = "IN";
            }
            if (st == "ORE")
            {
                st = "OR";
            }
            ud.UserState = st;


            ud.Organization = amember.GetValue("organization").ToString();

            ud.UserRole = GetRoleOfUser(email);

            ud.UserId = amember.Id.ToString();

            string jsonString = JsonConvert.SerializeObject(ud);

            string encryptString = UmbracoShipTac.Code.Encryptor.StringCipher.Encrypt(jsonString, paraphrase);

            // string DecrptString = UmbracoShipTac.Code.Encryptor.StringCipher.Decrypt(encryptString, paraphrase);

            return(encryptString);
        }
        public UserDetail InsertUserDetail(int vUserDetailID, string vUserId, string vFirstName,
                                           string vLastName, int vAddressId, int vContactInfoId, DateTime vAddedDate, string vAddedBy,
                                           DateTime vUpdatedDate, string vUpdatedBy, bool vActive, string vPassword)
        {
            UserDetail lUserDetail = new UserDetail();

            using (FRShoppingEntities frctx = new FRShoppingEntities())
            {
                if (vUserDetailID > 0)
                {
                    lUserDetail               = frctx.UserDetails.FirstOrDefault(u => u.UserDetailId == vUserDetailID);
                    lUserDetail.UserId        = vUserId;
                    lUserDetail.FirstName     = vFirstName;
                    lUserDetail.LastName      = vLastName;
                    lUserDetail.AddressId     = vAddressId;
                    lUserDetail.ContactInfoId = vContactInfoId;

                    lUserDetail.UpdatedDate = vUpdatedDate;
                    lUserDetail.UpdatedBy   = vUpdatedBy;
                    lUserDetail.Active      = vActive;
                    //lUserDetail.Password = vPassword;
                    return(frctx.SaveChanges() > 0 ? lUserDetail : null);
                }
                else
                {
                    lUserDetail.UserId        = vUserId;
                    lUserDetail.FirstName     = vFirstName;
                    lUserDetail.LastName      = vLastName;
                    lUserDetail.AddressId     = vAddressId;
                    lUserDetail.ContactInfoId = vContactInfoId;
                    lUserDetail.Password      = vPassword;

                    lUserDetail.AddedDate   = vAddedDate;
                    lUserDetail.AddedBy     = vAddedBy;
                    lUserDetail.UpdatedDate = vUpdatedDate;
                    lUserDetail.UpdatedBy   = vUpdatedBy;
                    lUserDetail.Active      = vActive;
                    return(AddUserDetail(lUserDetail));
                }
            }
        }
Esempio n. 25
0
        public VendorsBeautyService AddBeautyService(VendorsBeautyService vendorBeautyService, Vendormaster vendorMaster)
        {
            string updateddate = DateTime.UtcNow.ToShortDateString();

            vendorBeautyService.UpdatedDate = Convert.ToDateTime(updateddate);
            vendorBeautyService.Status      = "Active";
            vendorMaster.UpdatedDate        = userLogin.RegDate = userLogin.UpdatedDate = Convert.ToDateTime(updateddate);
            vendorMaster.Status             = userLogin.Status = "Active";
            vendorMaster.ServicType         = "BeautyServices";
            vendorMaster = vendorMasterRepository.AddVendorMaster(vendorMaster);
            vendorBeautyService.VendorMasterId = vendorMaster.Id;
            vendorBeautyService           = vendorBeautyServiceRespository.AddBeautyService(vendorBeautyService);
            userLogin.UserName            = vendorMaster.EmailId;
            userLogin.Password            = randomPassword.GenerateString();
            userLogin.UserType            = "Vendor";
            userLogin.UpdatedBy           = 2;
            userLogin                     = userLoginRepository.AddVendorUserLogin(userLogin);
            userDetail.UserLoginId        = userLogin.UserLoginId;
            userDetail.FirstName          = vendorMaster.BusinessName;
            userDetail.UserPhone          = vendorMaster.ContactNumber;
            userDetail.Url                = vendorMaster.Url;
            userDetail.Address            = vendorMaster.Address;
            userDetail.City               = vendorMaster.City;
            userDetail.State              = vendorMaster.State;
            userDetail.ZipCode            = vendorMaster.ZipCode;
            userDetail.Status             = "Active";
            userDetail.UpdatedBy          = ValidUserUtility.ValidUser();
            userDetail.UpdatedDate        = Convert.ToDateTime(updateddate);
            userDetail.AlternativeEmailID = vendorMaster.EmailId;
            userDetail.Landmark           = vendorMaster.Landmark;
            userDetail                    = userDetailsRepository.AddUserDetails(userDetail);
            if (vendorMaster.Id != 0 && vendorBeautyService.Id != 0 && userLogin.UserLoginId != 0 && userDetail.UserDetailId != 0)
            {
                return(vendorBeautyService);
            }
            else
            {
                vendorBeautyService.Id = 0;
                return(vendorBeautyService);
            }
        }
Esempio n. 26
0
        public ActionResult AddUser(FormCollection fc, HttpPostedFileBase photo, HttpPostedFileBase document)
        {
            if (ModelState.IsValid)
            {
                UserDetail user = new UserDetail();

                user.FirstName = fc["FirstName"];
                user.LastName  = fc["LastName"];
                user.Address   = fc["Address"];
                //user.FileAddress = fc["FileAddress"];

                user.CityName    = fc["CityName"];
                user.Latitude    = decimal.Parse(fc["Latitude"]);
                user.Longitude   = decimal.Parse(fc["Longitude"]);
                user.Description = fc["Description"];
                //user.PhotoPath = fc["PhotoPath"];
                user.RegisterDate = DateTime.Now.ToLocalTime();
                user.mapAddress   = fc["map"];


                if (photo != null && photo.ContentLength > 0)
                {
                    string fileName = Path.GetFileName(photo.FileName);
                    string imgpath  = Path.Combine(Server.MapPath("~/Files/Images/"), DateTime.Now.ToLongDateString() + fileName);
                    photo.SaveAs(imgpath);
                    user.PhotoPath = DateTime.Now.ToLongDateString() + fileName;
                }

                if (document != null && document.ContentLength > 0)
                {
                    string fileName = Path.GetFileName(document.FileName);
                    string imgpath  = Path.Combine(Server.MapPath("~/Files/Images/"), DateTime.Now.ToLongDateString() + fileName);
                    document.SaveAs(imgpath);
                    user.FileAddress = DateTime.Now.ToLongDateString() + fileName;
                }

                db.UserDetails.Add(user);
                db.SaveChanges();
            }
            return(RedirectToAction("Index", "Home"));
        }
        private string InitiateICR(PurchaseOrderItem item, int RecordId, UserDetail currentUser, CompanyDetail company, int WorkFlowId)
        {
            ItemChangedDetailsAC itemChange = new ItemChangedDetailsAC
            {
                IsPOItemIcr          = true,
                IsPriceChangeRequest = true,
                ItemId              = item.ItemId,
                ModifyingCostPrice  = item.ReceivingCostPrice,
                ModifyingSellPrice  = item.ItemProfile.SellPrice,
                ModifyingSellPriceA = item.ItemProfile.SellPriceA,
                ModifyingSellPriceB = item.ItemProfile.SellPriceB,
                ModifyingSellPriceC = item.ItemProfile.SellPriceC,
                ModifyingSellPriceD = item.ItemProfile.SellPriceD,
                POItemId            = item.Id,
                RequestedDate       = DateTime.UtcNow,
                ParentRecordId      = RecordId,
                IsInDirect          = true
            };

            return(_iICRRepository.SaveICR(itemChange, currentUser, company, WorkFlowId));
        }
Esempio n. 28
0
        public UserDetail RejectUserPendingRequest(UserDetail userDetail)
        {
            var param = new SqlParameter[]
            {
                new SqlParameter("@ID", userDetail.ID),
                new SqlParameter("@GlobalID", userDetail.GlobalID),
                new SqlParameter("@UserName", userDetail.UserName),
                new SqlParameter("@Email", userDetail.EmailID),
                new SqlParameter("@ContactNo", userDetail.ContactNo),
                new SqlParameter("@CreditAmountID", userDetail.CreditAmountID),
                new SqlParameter("@DepartmentID", userDetail.DepartmentID),
                new SqlParameter("@ApprovalStatus", false),
                new SqlParameter("@Comments", userDetail.Comments),
                new SqlParameter("@RequesterEmail", userDetail.RequesterEmail),
                new SqlParameter("@IsRequesterNotified", false),
                new SqlParameter("@IsAdminNotified", false),
                new SqlParameter("@RecordStatusId", 1)
            };

            return(SqlHelper.ExecuteProcedureReturnSingleObject <UserDetail>(ConnectionString, SPConstants.uspSaveUserAccessRequest, param));
        }
Esempio n. 29
0
        public IActionResult LoginUser(UserDetail ud)
        {
            UserMethod        um    = new UserMethod();
            List <UserDetail> users = new List <UserDetail>();
            string            error = "";

            users = um.GetUsers(out error);
            UserDetail currentUser = users.Find(user => user.Username == ud.Username);

            if (currentUser != null)
            {
                string usr = JsonConvert.SerializeObject(currentUser);
                HttpContext.Session.SetString("currentuser", usr);
                return(View("UserSettings", currentUser));
            }
            else
            {
                ViewBag.error = "Inloggningsuppgifterna stämmer inte.";
                return(View());
            }
        }
Esempio n. 30
0
 public ActionResult BasicInformation()
 {
     if (Session["UserId"] != null)
     {
         int        UserId   = Convert.ToInt32(Session["UserId"].ToString());
         UserDetail Userdata = UserInfoService.Get(UserId);
         ProfileBasicInformation BasicProfile = new ProfileBasicInformation()
         {
             FirstName  = Userdata.FirstName,
             LastName   = Userdata.LastName,
             DOB        = Userdata.DOB,
             Salutation = SalutationService.GetSaluations(),
             //States = StatecitydistrictService.GetAllStates(),
             SalutationId   = Userdata.SalutationId,
             GenderId       = Convert.ToInt32(Userdata.GenderId),
             ProfilePicture = Userdata.ProfilePicture
         };
         return(View(BasicProfile));
     }
     return(RedirectToAction("Login", "Account", new { area = "" }));
 }
Esempio n. 31
0
        private async void btnsave_Clicked(object sender, EventArgs e)
        {
            Datamanager dataManager = new Datamanager();

            users = new UserDetail()
            {
                Username  = name.Text,
                UserPhone = phone.Text,
                UserEmail = email.Text,
                Savetime  = DateTime.Now.ToShortTimeString()
            };
            int result = await dataManager.SaveUserDetailAsync(users);

            if (result == 1)
            {
                name.Text  = string.Empty;
                phone.Text = string.Empty;
                email.Text = string.Empty;
                await DisplayAlert("", "Record Saved", "OK");
            }
        }
        public LoginValidate SignUp([FromBody] UserDetail usr)
        {
            Login         db = new Login();
            LoginValidate lv = new LoginValidate();
            UserDetail    u  = db.SignIn(usr.userName);

            if (u != null)
            {
                lv.loginStatus = -1; //User already Exist
                lv.accType     = "";
                lv.token       = "";
            }
            else
            {
                db.SignUp(usr);
                lv.loginStatus = 1; //Signup Successful
                lv.accType     = "";
                lv.token       = "";
            }
            return(lv);
        }
Esempio n. 33
0
        public async Task <ActionResult <UserDetail> > GetCurrentUser()
        {
            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            if (user == null)
            {
                return(NotFound());
            }

            var result = new UserDetail
            {
                Id = user.Id,
                isAdministrator        = user.IsAdministrator,
                UserName               = user.UserName,
                PasswordExpired        = user.PasswordExpired,
                DaysTillPasswordExpiry = PasswordExpiryHelper.ContDaysTillPasswordExpiry(user, _userOptionsExtended),
                Permissions            = user.Roles.SelectMany(x => x.Permissions).Select(x => x.Name).Distinct().ToArray()
            };

            return(Ok(result));
        }
Esempio n. 34
0
        public async Task <IActionResult> PutAnItem(int id, [FromBody] UserDetail item)
        {
            try
            {
                if (id != item.Id)
                {
                    return(BadRequest());
                }

                _context.Entry(item).State          = EntityState.Modified;
                _context.Entry(item.UserInfo).State = EntityState.Unchanged;
                await _context.SaveChangesAsync();

                return(AcceptedAtAction(nameof(GetById), new { id = item.Id }, item));
            }
            catch (Exception ex)
            {
                Log.ForContext <UserDetailsController>().Error(ex.Message);
                return(BadRequest(ex.Message));
            }
        }
Esempio n. 35
0
        public void GetMethodCallRetrunsExeExpectedResult()
        {
            // Arrange
            var mockUserDetail = new UserDetail {
                Id = 1, FirstName = "Thiru", LastName = "Vasan"
            };
            var movieCruiserDbContext = new Mock <AuthServiceDbContext>();
            var dbSetMock             = new Mock <DbSet <UserDetail> >();

            movieCruiserDbContext.Setup(x => x.Set <UserDetail>()).Returns(dbSetMock.Object);
            dbSetMock.Setup(x => x.Find(It.IsAny <int>())).Returns(mockUserDetail);
            repository = new Repository(movieCruiserDbContext.Object);

            // Act
            var result = repository.Get <UserDetail>(1);

            // Assert
            movieCruiserDbContext.Verify(x => x.Set <UserDetail>());
            dbSetMock.Verify(x => x.Find(It.IsAny <int>()));
            Assert.Equal(1, result.Id);
        }
Esempio n. 36
0
        private AudienceResponse TokenMapper(User audience, Guid token, string message = "")
        {
            var        webUrl           = ConfigurationManager.AppSettings["WebUrl"] + "/";
            var        userCardDetail   = _userRepository.GetUserCardDetailsByUserId(audience.Id);
            UserDetail userDetailReturn = new UserDetail();

            userDetailReturn.UserId           = audience.Id;
            userDetailReturn.Email            = audience.Email;
            userDetailReturn.IsVerified       = audience.IsVerified;
            userDetailReturn.AccessToken      = token;
            userDetailReturn.Message          = message;
            userDetailReturn.IsCardRegistered = userCardDetail != null ? true : false;
            userDetailReturn.UserCode         = webUrl + "UserCodes/" + audience.UserCode + ".jpeg";

            var validateResponse = new AudienceResponse
            {
                data = userDetailReturn,
            };

            return(validateResponse);
        }
Esempio n. 37
0
 protected void btnChangePicture_Click(object sender, EventArgs e)
 {
     try
     {
         UserDetail ud = new UserDetail();
         ud.UpdatePicture("Student/" + FileUpload1.FileName, txtStudentID.Text);
         FileUpload1.SaveAs(Server.MapPath("~/Student/" + FileUpload1.FileName));
         lblMessage.ForeColor = System.Drawing.Color.Black;
         lblMessage.Text      = "Successfully Updated!";
         txtStudentID.Text    = "";
         txtStudentName.Text  = "";
         txtRollNumber.Text   = "";
         txtUsername.Text     = "";
         txtEmail.Text        = "";
         txtStudentID.Focus();
     }
     catch (Exception) {
         lblMessage.ForeColor = System.Drawing.Color.Red;
         lblMessage.Text      = "Cannot Update Picture";
     }
 }
Esempio n. 38
0
        /// <summary>
        /// sipriş yetki düzenleme sayfası
        /// </summary>
        public PartialViewResult Parametre(int ID)
        {
            if (CheckPerm(Perms.Kullanıcılar, PermTypes.Reading) == false || ID == 1)
            {
                return(null);
            }
            ViewBag.ID = ID;
            var tbl = db.UserDetails.Where(m => m.UserID == ID).FirstOrDefault();

            if (tbl == null)
            {
                tbl = new UserDetail()
                {
                    GostCHKKodAlani   = "0;ZZZ",
                    GostKod3OrtBakiye = "0, 999999999999, 0, 0",
                    GostRiskDeger     = "0, 999999999999, 0, 0"
                }
            }
            ;
            return(PartialView("Parametre", tbl));
        }
Esempio n. 39
0
        public IActionResult ProfileData()
        {
            UserDetail model = new UserDetail();
            var        user  = HttpContext.Session.Get <UserViewModel>(Constants.SessionKeyUserInfo);

            user = user ?? new UserViewModel();
            try
            {
                ViewBag.JobIndustryArea  = jobpastHandler.GetJobIndustryAreaDetails();
                ViewBag.EmploymentStatus = jobpastHandler.GetJobJobEmploymentStatusDetails();
                ViewBag.Country          = jobpastHandler.GetCountryDetails();

                model = userProfileHandler.GetJobseekerDetail(user.UserId);
            }
            catch (DataNotFound ex)
            {
                Logger.Logger.WriteLog(Logger.Logtype.Error, ex.Message, user.UserId, typeof(JobSeekerManagementController), ex);
                ModelState.AddModelError("ErrorMessage", string.Format("{0}", ex.Message));
            }
            return(new JsonResult(model, ContractSerializer.JsonInPascalCase()));
        }
Esempio n. 40
0
        public async Task ResetUser(UserDetail target)
        {
            int id = 0;

            if (int.TryParse(target.GroupId, out id))
            {
                var channel = await _db.Channels.Include(i => i.Users).FirstOrDefaultAsync(i => i.Id == id);

                if (channel.OwnerId != target.UserId)
                {
                    var channelUserDb = await _db.ChannelUsers.FirstOrDefaultAsync(i => i.ChannelId == id && i.UserId.Equals(target.UserId));

                    channelUserDb.State = (int)UserStates.Joined;
                    target.State        = channelUserDb.State;

                    await _db.SaveChangesAsync();

                    await UpdateState(target);
                }
            }
        }
Esempio n. 41
0
        public int editUserProfile(UserDetailsView model, string email)
        {
            UserDetail userDetail = db.UserDetails.FirstOrDefault(x => x.email == email);

            userDetail.adress = model.Address;
            userDetail.email  = model.Email;
            userDetail.name   = model.Name;
            userDetail.phone  = model.Phone;

            try
            {
                // db.UserDetails.Add(userDetail);

                db.SaveChanges();
                return(1);
            }
            catch
            {
                return(0);
            }
        }
Esempio n. 42
0
        public string AddUserDetails(UserLogin userLogin, UserDetail userDetails)
        {
            string response;
            //userLogin.Status = "Active";
            DateTime updateddate = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE);//DateTime.UtcNow.ToShortDateString();

            userLogin.RegDate     = updateddate;
            userLogin.UpdatedDate = userDetails.UpdatedDate = updateddate;
            try
            {
                UserLogin l1 = userLoginRepository.AddLoginCredentials(userLogin);
                userDetails.UserLoginId = l1.UserLoginId;
                UserDetail l2 = userDetailsRepository.AddUserDetails(userDetails);
                response = "sucess";
            }
            catch (Exception ex)
            {
                response = "failure";
            }
            return(response);
        }
Esempio n. 43
0
        public int Insert2(UserDetailsInsertModel model, string Email)
        {
            UserDetail userDetail = new UserDetail();

            userDetail.adress = model.Address;
            userDetail.email  = Email;
            userDetail.name   = model.Name;
            userDetail.phone  = model.Phone;
            userDetail.point  = 50;
            try
            {
                db.UserDetails.Add(userDetail);

                db.SaveChanges();
                return(1);
            }
            catch
            {
                return(0);
            }
        }
Esempio n. 44
0
        public IHttpActionResult Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new UserDetail()
            {
                UserName = model.Email, Email = model.Email
            };

            var result = userManagementService.CreateUser(user, model.Password);

            if (result.HasError)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
        public IActionResult DelEquip(int EquipID)
        {
            var result = db.Equips.Where(x => x.EquipID == EquipID).FirstOrDefault();

            db.Remove(result);
            db.SaveChanges();
            var UserDetail  = new UserDetail();
            var equipDetail = from a in db.Equips
                              join b in db.Types on a.TypeID equals b.TypeID
                              select new EquipInfo
            {
                EquipName   = a.EquipName,
                EquipDes    = a.EquipDes,
                EquipStatus = a.EquipStatus,
                TypeName    = b.TypeName,
                EquipID     = a.EquipID
            };

            UserDetail.EquipInfos = equipDetail.ToList();
            return(View("ShowEquip", UserDetail));
        }
Esempio n. 46
0
        public int createUser(UserDetail user)
        {
            int result = 0;

            if (user.password == user.confirmPW)
            {
                bool check = _user.NewAccount(user);
                if (check == true)
                {
                    SelectList x = new SelectList(_user.getAllDonVi(), "Value", "Name", user.don_vi_ref);
                    ViewBag.lstDonVi = x;
                }
            }
            else
            {
                SelectList x = new SelectList(_user.getAllDonVi(), "Value", "Name", user.don_vi_ref);
                ViewBag.lstDonVi = x;
                result           = 1;
            }
            return(result);
        }
Esempio n. 47
0
        public HttpResponseMessage PostUserSearch(Inner data)
        {
            AllString ob = new AllString();

            try
            {
                UserDetail uDetail = new UserDetail();
                UserData   ud      = DapperHelper.Search <UserData>(SamgoGameHelper.connectionString,
                                                                    "exec [samgo_get_user_info] N'" + data.Role + "', N'" + data.Legion + "'").FirstOrDefault();
                uDetail = DapperHelper.Search <UserDetail>(SamgoGameHelper.connectionString,
                                                           "exec [samgo_get_user_tech_info] N'" + data.Role + "', N'" + data.Legion + "'").FirstOrDefault();
                SamgoGameHelper.ConvertDataToModels(ref ob, ud, uDetail);
            }
            catch (Exception) { }
            if (ob.Role == null)
            {
                ob.Role   = data.Role;
                ob.Legion = data.Legion;
            }
            return(Request.CreateResponse(HttpStatusCode.OK, ob));
        }
    //This function will send emails in background...
    public void SendRegisterEmail(UserDetail userInfo, Pollinator.DataAccess.PolinatorInformation pollinator)
    {
        phEmailTasks.Controls.Add(new LiteralControl("<iframe src='" + ResolveUrl("../AsyncSendEmail") + "' id='AsyncSendEmails' scrolling='no'></iframe>"));

        var emails = new List<ConfirmationEmailTemplate>();

        var userEmailTemplate = GetUserEmailTemplate(userInfo, pollinator);
        emails.Add(userEmailTemplate); //Add emailing for new user

        //var Administrators = new List<string>();
        //Administrators.Add("Truong"); //Dummy data, must be replaced with real Admin name

        foreach (var adminEmail in GetListAdmin())
        {
            var adminName = adminEmail.Substring(0, adminEmail.IndexOf("@"));
            var adminEmailTemplate = GetAdminEmailTemplate(adminName, adminEmail, userInfo, pollinator);
            emails.Add(adminEmailTemplate); //Add emailing for Administrators
        }

        //Put them all in session object which will be retrieved in Async process running in background
        Session["Emails"] = emails;
    }
Esempio n. 49
0
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            MembershipUser usr = Membership.GetUser(UserID);

            var userDetail = GetUser();
            if (userDetail==null)
                userDetail = new UserDetail();

            var polinatorInformation = GetPolinatorInfo();
            if (polinatorInformation == null)
                polinatorInformation = new PolinatorInformation();

            //status
            polinatorInformation.IsApproved = false;//reset IsApproved = 0
            polinatorInformation.IsNew = false;
            polinatorInformation.LastUpdated = DateTime.Now;

            //get new values from form and set to object to update
            GetValueFromControlPrenium(usr, userDetail, polinatorInformation);

            if (usr != null)
                Membership.UpdateUser(usr);

            mydb.SaveChanges();
            //StatusMessage.Text = "<strong>Update successful!</strong>";
            //GoToAlertMessage(panelSuccessMessage);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "document.getElementById('confirm_pop').click();", true);

            //Response.Redirect("~/ShareMap.aspx");
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
            Pollinator.Common.Logger.Error("Error occured at " + typeof(Members_UserUpdate).Name + ".btnUpdate_Click(). Exception:" + ex.Message);
            GoToAlertMessage(panelErrorMessage);
        }
    }
Esempio n. 50
0
    void btnRegister_Click(object sender, EventArgs e)
    {
        lblThankYouMessage.Text = "Thank you for registering pollinator information with Pollinator Partnership. An email has been sent to contact emails associated with your account. Please be patient; the delivery of email may be delayed. Remember to confirm that the email above is correct and to check your junk or spam folder or filter if you do not receive this email.";

        UserDetail userInfo = new UserDetail();
        var pollinator = new Pollinator.DataAccess.PolinatorInformation();

        //----------------NOTE: You have to supply the real data to replace this dummy data------------------
        userInfo.UserId = new Guid();
        userInfo.FirstName = "Truong";
        userInfo.PhoneNumber = "0904949821";

        pollinator.OrganizationName = "Natural Resources Conservation Service";
        pollinator.LandscapeStreet = "Duy Tan";
        pollinator.LandscapeCity = "Hanoi";
        pollinator.LandscapeState = "CA";
        pollinator.LandscapeZipcode = "01";
        pollinator.PollinatorSize = 1;
        pollinator.PollinatorType = 1;

        SendRegisterEmail(userInfo, pollinator);
    }
        public static string updateImage(UserDetail ud)
        {
            try {
                UserDetail usr = dataContext.UserDetails.First(i => i.fname == ud.fname && i.address == ud.address);

                usr.pic = ud.pic;

                dataContext.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}",
                                                validationError.PropertyName,
                                                validationError.ErrorMessage);
                    }
                }
            }
            return "success";
        }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        UserDetail ud = new UserDetail();
        try
        {
            string hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1");
            DataTable dt = ud.CheckMember(txtUsername.Text, hashedPassword);

            if (dt.Rows.Count > 0)
            {
                Session["Member"] = txtUsername.Text;
                Response.Redirect("Home.aspx");
            }
            else
            {
                ltrMessage.Text = "Invallid User or Password!";
            }
        }
        catch (Exception ex)
        {
            ltrMessage.Text = ex.Message;
        }
        
    }
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Token = Member.AdminToken;

            if (!Token.IsEmpty())
            {
                LoginUserDetail = Member.GetLoginMember(Token);

                //用户存在并且是管理人员
                if (LoginUserDetail != null &&
                    (LoginUserDetail.IsStaff || LoginUserDetail.IsLegal || LoginUserDetail.IsShopkeeper ||
                     LoginUserDetail.IsManager))
                {
                    ViewData["UserName"] = LoginUserDetail.Nick;
                    base.OnActionExecuting(filterContext);

                    return;
                }
            }

            filterContext.Result =
                new RedirectResult(Url.Action("Index", "Login",
                    new {returnurl = HttpUtility.UrlEncode(Request.Url.ToString())}));
        }
Esempio n. 54
0
        public void Connect(string userName, string eventName)
        {
            var id = Context.ConnectionId;
            if (ConnectedUsers.Count(x => x.ConnectionId == id) > 0) return;

            UserDetail user = new UserDetail { ConnectionId = id, UserName = userName, Event = eventName };

            if (ConnectedUsers.FirstOrDefault(u => u.UserName == userName) == null)
            {
                ConnectedUsers.Add(user);
            }
            else
            {
                ConnectedUsers.FirstOrDefault(u => u.UserName == userName).ConnectionId = id;
                ConnectedUsers.FirstOrDefault(u => u.UserName == userName).Event = eventName;
            }

            this.Groups.Add(id, eventName);
            // send to caller
            Clients.Caller.onConnected(id, userName, GetSameGroupUsers(userName), SameGroupMessage(userName));

            // send to all except caller client
            //Clients.AllExcept(GetOtherGroupUsers(userName)).onNewUserConnected(id, userName);
        }
Esempio n. 55
0
    /// <summary>
    /// Custom display at top of site
    /// (1)Set logonName display FirstName
    /// (2)Set Premium Since MMM, yyyy
    /// </summary>
    private void SetMessageAfterLogin()
    {
        try
        {
            //if (Context.User.Identity.IsAuthenticated)
            //{
            //    string test = HttpUtility.HtmlEncode(@"<newuser2>?:!@#%^&*()_+""'.,/\[]|\!@#$%^&*()_+");
            //    //test = "&lt;newuser2&gt;?:{}|\\!@#$%^&amp;*()_+";
            //    LoginName loginName1 = (LoginName)LoginView2.FindControl("loginName");
            //    loginName1.FormatString = test;
            //}

            if (Context.User.Identity.IsAuthenticated && Roles.IsUserInRole(Utility.RoleName.Members.ToString()))
            {
                string sesloginName = "loginName" + Context.User.Identity.Name;
                string sesPreSince = "aPreSince" + Context.User.Identity.Name;

                LoginName loginName = (LoginName)LoginView2.FindControl("loginName");
                if (Session[sesloginName] != null)
                    loginName.FormatString = Session[sesloginName].ToString();

                HtmlAnchor aPreSince = (HtmlAnchor)LoginView2.FindControl("aPreSince");
                if (Session[sesPreSince] != null)
                    aPreSince.InnerText = Session[sesPreSince].ToString();
                else
                {
                    Guid userID = (Guid)System.Web.Security.Membership.GetUser(Context.User.Identity.Name).ProviderUserKey;
                    PollinatorEntities mydb = new PollinatorEntities();
                    UserDetail userDetail = new UserDetail();

                    var selectedUserDetail = (from user in mydb.UserDetails
                                              where user.UserId == userID
                                              select user).FirstOrDefault();

                    if (selectedUserDetail != null)
                    {
                        //set loginName
                        Session[sesloginName] = selectedUserDetail.FirstName;
                        loginName.FormatString = HttpUtility.HtmlEncode(Session[sesloginName].ToString());

                        if (selectedUserDetail.MembershipLevel == 0)
                            aPreSince.Visible = false;
                        else if (selectedUserDetail.MembershipLevel > 0)
                        {
                            var pollinatorInfomation = (from poll in mydb.PolinatorInformations
                                                        where poll.UserId == userID
                                                        select poll).FirstOrDefault();
                            DateTime paidDate = pollinatorInfomation.PaidDate == null ? DateTime.MinValue : (DateTime)pollinatorInfomation.PaidDate;
                            if (paidDate > DateTime.MinValue)
                            {
                                aPreSince.Visible = true;
                                Session[sesPreSince] = string.Format("Premium since {0}", String.Format("{0:MMM, yyyy}", paidDate));
                                aPreSince.InnerText = Session[sesPreSince].ToString();
                            }
                        }
                    }
                }
            }
            else if (Context.User.Identity.IsAuthenticated)
            {
                string sesloginName = "loginName" + Context.User.Identity.Name;
                string sesPreSince = "aPreSince" + Context.User.Identity.Name;

                HtmlAnchor aPreSince = (HtmlAnchor)LoginView2.FindControl("aPreSince");
                aPreSince.Visible = false;

                LoginName loginName = (LoginName)LoginView2.FindControl("loginName");
                if (Session[sesloginName] != null)
                    loginName.FormatString = Session[sesloginName].ToString();
                else
                {
                    Guid userID = (Guid)System.Web.Security.Membership.GetUser(Context.User.Identity.Name).ProviderUserKey;
                    PollinatorEntities mydb = new PollinatorEntities();
                    UserDetail userDetail = new UserDetail();

                    var selectedUserDetail = (from user in mydb.UserDetails
                                              where user.UserId == userID
                                              select user).FirstOrDefault();

                    if (selectedUserDetail != null)
                    {
                        //set loginName
                        Session[sesloginName] = selectedUserDetail.FirstName;
                        loginName.FormatString = Session[sesloginName].ToString();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            //write log
            Pollinator.Common.Logger.Error("Occured in function: " + typeof(SiteMap).Name + ".SetMessageAfterLogin()", ex);
        }
    }
Esempio n. 56
0
 public UserDetailFrm()
 {
     InitializeComponent();
     _userDetail = new UserDetail();
 }
Esempio n. 57
0
 public void TestSaveUser()
 {
     var sessionFactory = NhContext.CurrentFactory;
     using (var session = sessionFactory.OpenSession())
     {
         using (var tran = session.BeginTransaction())
         {
             var user = new User { Password = "", UserName = "******", CreateTime = DateTime.Now };
             var userDetail = new UserDetail { LastUpdated = DateTime.Now, Name = new PersionName { FirstName = "小明", LastName = "小明家族" } };
             userDetail.User = user;
             user.Detail = userDetail;
             session.Save(user);
             tran.Commit();
         }
     }
 }
Esempio n. 58
0
        public static async void SaveAsync(string filename, object obj)
        {
            /*
            //this use the Local folder but can be other
            
            var applicationData = ApplicationData.Current;
            var storageFolder = applicationData.LocalFolder;

            var file = await storageFolder.CreateFileAsync("User.xml", CreationCollisionOption.ReplaceExisting);

            var dataContractSerializer = new DataContractSerializer(obj.GetType());
            var memoryStream = new MemoryStream();
            dataContractSerializer.WriteObject(memoryStream, obj);
            memoryStream.Seek(0, SeekOrigin.Begin);

            string serialized = new StreamReader(memoryStream).ReadToEnd();
            memoryStream.Dispose();


            var doc = new XmlDocument();
            doc.LoadXml(serialized);

            await doc.SaveToFileAsync(file);
            */


            MessageDialog dialog;
            // Declare Variables
            StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile xmlFile = null;

            try
            {
                xmlFile = await storageFolder.GetFileAsync("filePathList.xml");
            }
            catch (FileNotFoundException ex)
            {
                string message = ex.Message;
            }

            // If xml file doesn't exist, make it with initial setting
            if (xmlFile == null)
            {
                String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><files></files>";
                var doc = new XmlDocument();
                doc.LoadXml(xml);

                // save xml to a file
                xmlFile = await storageFolder.CreateFileAsync("filePathList.xml"
                    , Windows.Storage.CreationCollisionOption.GenerateUniqueName);
                await doc.SaveToFileAsync(xmlFile);

                // Add permission to the files
                StorageApplicationPermissions.FutureAccessList.Add(xmlFile);
            }

            // Make XmlDom and init variable with the file
            XmlDocument xmlDoc = await XmlDocument.LoadFromFileAsync(xmlFile);
            XmlElement root = xmlDoc.DocumentElement;

            // Check duplicated name
            XmlNodeList fileNodeList = root.GetElementsByTagName("file");
            if (!(fileNodeList.Count() == 0))
            {
                foreach (XmlElement fileNode in fileNodeList)
                {
                    string munoramaName = fileNode.GetAttribute("id");
                    if (filename.Equals(munoramaName))
                    {
                        // Create the message dialog and set its content
                        dialog = new Windows.UI.Popups.MessageDialog("이미 같은 이름의 파일이 있습니다. 다른 이름으로 만들어 주세요.");
                        dialog.Commands.Add(new Windows.UI.Popups.UICommand("OK"));
                        dialog.DefaultCommandIndex = 0;
                        dialog.CancelCommandIndex = 1;
                        await dialog.ShowAsync();
                        return;
                    }
                }
            }

            // Get file element
            XmlElement file = xmlDoc.CreateElement("file");
            file.SetAttribute("id", filename);

            // Get MyCanvas Element
            XmlElement newcanvas = xmlDoc.CreateElement("canvas");
           
            Canvas canvas_save = obj as Canvas;
            var memoryStream = new MemoryStream();
            UserDetail Stats = new UserDetail();
            Type each_type;
            while (canvas_save.Children.Count!=0) {
                each_type = canvas_save.Children.First().GetType();
                Stats.Type_of = each_type.ToString();
                
                if (each_type == typeof(Line))
                {
                    Line thisline = canvas_save.Children.First() as Line;
                    Stats.Points_X1 = thisline.X1;
                    Stats.Points_Y1 = thisline.Y1;
                    Stats.Points_X2 = thisline.X2;
                    Stats.Points_Y2 = thisline.Y2;
                    
                    Brush brush = thisline.Stroke;
                    Stats.Color_of_A = ((Color)brush.GetValue(SolidColorBrush.ColorProperty)).A;
                    Stats.Color_of_G = ((Color)brush.GetValue(SolidColorBrush.ColorProperty)).G;
                    Stats.Color_of_R = ((Color)brush.GetValue(SolidColorBrush.ColorProperty)).R;
                    Stats.Color_of_B = ((Color)brush.GetValue(SolidColorBrush.ColorProperty)).B;
                    
                    //Stats.Brush_of = thisline.Stroke;
                    //Stats.Stretch_of = thisline.Stretch;
                }

                else if (each_type == typeof(TextBox))
                {
                    TextBox thistextbox = canvas_save.Children.First() as TextBox;
                    Stats.Points_X1 = Canvas.GetLeft(thistextbox);
                    Stats.Points_Y1 = Canvas.GetTop(thistextbox);
                    Stats.Points_X2 = Canvas.GetLeft(thistextbox) + thistextbox.Width;
                    Stats.Points_Y2 = Canvas.GetTop(thistextbox) + thistextbox.Height;
                    //Stats.Brush_of = thistextbox.Background;
                    Stats.Name = thistextbox.Text;
                    Stats.Id = int.Parse(thistextbox.Text);
                }
                //140517새벽

                var dataContractSerializer = new DataContractSerializer(typeof(UserDetail));
                dataContractSerializer.WriteObject(memoryStream, Stats);
                canvas_save.Children.RemoveAt(0);
            }
            memoryStream.Seek(0, SeekOrigin.Begin);

            string serialized = new StreamReader(memoryStream).ReadToEnd();
            memoryStream.Dispose();
            newcanvas.InnerText = serialized;
            
            // Add elements to file node
            file.AppendChild(newcanvas);

            // Add file node to Root
            root.AppendChild(file);

            // Flush xml elements to xml file
            await xmlDoc.SaveToFileAsync(xmlFile);

            // Create the message dialog and set its content
            dialog = new Windows.UI.Popups.MessageDialog("성공적으로 새 파일을 만들었습니다. 목록에서 확인하세요.");
            dialog.Commands.Add(new Windows.UI.Popups.UICommand("OK"));
            dialog.DefaultCommandIndex = 0;
            dialog.CancelCommandIndex = 1;
            await dialog.ShowAsync();
        }
Esempio n. 59
0
    /// <summary>
    /// Final step, Import Data Into Database
    /// </summary>
    /// <param name="listRowImport">list needed import</param>
    /// <param name="actionForExistedData">3 option: skip, new, overwrite. default is null(new)</param>
    /// Create by: Hoai Phuong
    private void ImportDataIntoDatabase(List<ImportExportFields> listRowImport, string actionForExistedData = null)
    {
        //set status navigator bar: current active step = 3(import)
        SetStatusNavigationBar(3);

        //show please wait... popup
        //ScriptManager.RegisterStartupScript(this, this.GetType(), "popupWait", "document.getElementById('showProcessbar').click();", true);
        //lblErrorMess.Text = "Đang import vào sql db...";
        divExistedData.Visible = false;

        memberLevel = MemberLevel;

        DateTime createdDate = DateTime.Now;
        ImportExportFields writedata;
        Membership userDB;
        UserDetail userDetail;
        PolinatorInformation polinatorInformation;

        Guid userId;
        int numImport = 0;
        int numSkipExist = 0;

        List<string> listAddUserName = new List<string>();

        int numRecord = listRowImport.Count;
        for (int i = 0; i < numRecord; i++)
        {
            writedata = listRowImport.ElementAt(i);

            userDetail = new UserDetail();
            polinatorInformation = new PolinatorInformation();

            if (writedata.IsExistedData && actionForExistedData == "skip")
            {
                numSkipExist++;
                continue;
            }
            numImport++;
            if (!writedata.IsExistedData || actionForExistedData == "new")
            {
                if (!string.IsNullOrEmpty(writedata.Email))
                {
                    //generate new user
                    //auto gen UserName, Password

                    string userName = Utility.CreateRandomUserName(0);
                    string password = Utility.CreateRandomPassword(10);
                    listAddUserName.Add(userName);
                    //Exec create
                    userId = (Guid)System.Web.Security.Membership.CreateUser(userName, password, writedata.Email).ProviderUserKey;

                }
                else
                    userId = Guid.NewGuid();
            }
            else
            {
                //if (writedata.UserId != Guid.Empty)
                //    userId = writedata.UserId;
                //else

                userId = writedata.ExistedUserId;
                if (!string.IsNullOrEmpty(writedata.Email))
                {
                    userDB = (from us in mydb.Memberships
                              where us.UserId == userId
                              select us).FirstOrDefault();
                    userDB.Email = writedata.Email;
                }

                userDetail = (from ud in mydb.UserDetails
                              where ud.UserId == userId
                              select ud).FirstOrDefault();

                polinatorInformation = (from pi in mydb.PolinatorInformations
                                        where pi.UserId == userId
                                        select pi).FirstOrDefault();
            }

            userDetail.UserId = userId;
            userDetail.FirstName = writedata.FirstName;
            userDetail.LastName = writedata.LastName;
            userDetail.MembershipLevel = memberLevel;
            userDetail.PhoneNumber = writedata.PhoneNumber;

            //Table 2: polinatorInformation
            polinatorInformation.UserId = userId;

            polinatorInformation.OrganizationName = writedata.OrganizationName;
            polinatorInformation.Description = writedata.OrganizationDescription;
            polinatorInformation.PollinatorSize = writedata.PollinatorSize;
            polinatorInformation.PollinatorType = writedata.PollinatorType;
            polinatorInformation.LandscapeStreet = writedata.LandscapeStreet;
            polinatorInformation.LandscapeCity = writedata.LandscapeCity;
            polinatorInformation.LandscapeState = writedata.LandscapeState;
            polinatorInformation.LandscapeZipcode = writedata.LandscapeZipcode;
            polinatorInformation.LandscapeCountry = writedata.LandscapeCountry;
            polinatorInformation.Website = writedata.Website;

            polinatorInformation.IsApproved = true;
            polinatorInformation.IsNew = false;
            polinatorInformation.CreatedDate = createdDate;
            polinatorInformation.LastUpdated = createdDate;

            if (writedata.Latitude.HasValue && writedata.Longitude.HasValue)
            {
                polinatorInformation.Latitude = (decimal)writedata.Latitude;
                polinatorInformation.Longitude = (decimal)writedata.Longitude;
            }
            else
            {
                SetLalngByAddress(writedata, polinatorInformation);
            }

            polinatorInformation.SourceData = sourceData;

            if (!writedata.IsExistedData || actionForExistedData == "new")
            {
                mydb.UserDetails.Add(userDetail);
                mydb.PolinatorInformations.Add(polinatorInformation);
            }
        }

        try
        {
            mydb.SaveChanges();

            //show successfully panel
            lblMess.Visible = false;
            this.divImportSuccessful.Visible = true;
            this.lblTotalDataRecord.Text = TotalRecord.ToString();
            this.lblNumImported.Text = numImport.ToString();
            this.lblNumNotImported.Text = (TotalInvalidRecord + numSkipExist).ToString();
            this.lblNumInvalid.Text = TotalInvalidRecord.ToString();
            this.lblNumSkipExist.Text = numSkipExist.ToString();

            //show/hide link download log file
            if (TotalInvalidRecord == 0)
                lnkFinishInvalidLog.Visible = false;
            else lnkFinishInvalidLog.Visible = true;

            if (numSkipExist == 0)
                lnkFinishSkipLog.Visible = false;
            else lnkFinishSkipLog.Visible = true;

            //Write log
            var logContent = new StringBuilder();
            logContent.Append(string.Format("Total data records: {0}{1}", TotalRecord.ToString(), Environment.NewLine));
            logContent.Append(string.Format("Records imported: {0}{1}", numImport.ToString(), Environment.NewLine));
            logContent.Append(string.Format("Records ignored: {0}{1}", (TotalInvalidRecord + numSkipExist).ToString(), Environment.NewLine));
            logContent.Append(string.Format(" - Invalid records: {0}{1}", TotalInvalidRecord.ToString(), Environment.NewLine));
            logContent.Append(string.Format(" - Manually skipped: {0}{1}", numSkipExist.ToString(), Environment.NewLine));

            string fileName = "ImportSuccessful" + System.DateTime.Now.ToString("_yyMMdd_hhmm") + ".txt";
            ImportExportUltility.WriteFile(Request, fileName, logContent.ToString());

            //set status navigator bar: current active step = 3(Finish)
            SetStatusNavigationBar(4);
        }
        catch (Exception e)
        {
            //Delete added udername
            try
            {
                for (int i = 0; i < listAddUserName.Count; i++)
                {
                    System.Web.Security.Membership.DeleteUser(listAddUserName[i]);
                }
            }
            catch
            {
            }
            //Write log fie
            WriteImportFailLog(e);

            SetStatusNavigationBar(4);
            //show error panel
            this.divImportFail.Visible = true;
        }
    }
 public void Insert(UserDetail userDetail)
 {
     db.UserDetails.Add(userDetail);
     db.SaveChanges();
 }